Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

Add STS GetWebIdentityToken action (#506)

Nahuel Nucera84e24b30e2f7
diff --git a/ministack/services/sts.py b/ministack/services/sts.py
index 7d381e9a..f01f3a87 100644
--- a/ministack/services/sts.py
+++ b/ministack/services/sts.py
@@ -3,9 +3,12 @@ STS Service Emulator (AWS-compatible).
Actions:
GetCallerIdentity, AssumeRole, AssumeRoleWithWebIdentity,
- GetSessionToken, GetAccessKeyInfo.
+ GetSessionToken, GetAccessKeyInfo, GetWebIdentityToken.
"""
+import base64
+import hashlib
+import hmac
import json
import time
from urllib.parse import parse_qs
@@ -175,4 +178,91 @@ async def handle_request(method, path, headers, body, query_params):
f"</GetAccessKeyInfoResult>",
ns="sts")
+ if action == "GetWebIdentityToken":
+ # --- AWS-spec validation ---
+ # SigningAlgorithm: REQUIRED, must be RS256 or ES384.
+ signing_alg = _p(params, "SigningAlgorithm")
+ if not signing_alg:
+ return _error(400, "MissingParameter",
+ "The request must contain the parameter SigningAlgorithm.",
+ ns="sts")
+ if signing_alg not in ("RS256", "ES384"):
+ return _error(400, "ValidationError",
+ f"Value '{signing_alg}' at 'signingAlgorithm' failed to satisfy constraint: "
+ f"Member must satisfy enum value set: [RS256, ES384]",
+ ns="sts")
+
+ # Audience: REQUIRED, 1-10 items, each 1-1000 chars.
+ audiences = []
+ for k, v in params.items():
+ if k == "Audience" or k.startswith("Audience.member."):
+ vals = v if isinstance(v, list) else [v]
+ audiences.extend(vals)
+ if not audiences:
+ return _error(400, "MissingParameter",
+ "The request must contain the parameter Audience.",
+ ns="sts")
+ if len(audiences) > 10:
+ return _error(400, "ValidationError",
+ "1 validation error detected: Value at 'audience' failed to satisfy constraint: "
+ "Member must have length less than or equal to 10",
+ ns="sts")
+ for a in audiences:
+ if not (1 <= len(a) <= 1000):
+ return _error(400, "ValidationError",
+ "1 validation error detected: Value at 'audience' failed to satisfy constraint: "
+ "Member must have length between 1 and 1000",
+ ns="sts")
+
+ # DurationSeconds: optional, 60-3600, default 300.
+ try:
+ duration = int(_p(params, "DurationSeconds") or 300)
+ except (TypeError, ValueError):
+ return _error(400, "ValidationError",
+ "Value for DurationSeconds must be an integer.",
+ ns="sts")
+ if not (60 <= duration <= 3600):
+ return _error(400, "ValidationError",
+ f"1 validation error detected: Value '{duration}' at 'durationSeconds' "
+ f"failed to satisfy constraint: Member must have value between 60 and 3600",
+ ns="sts")
+
+ now = int(time.time())
+ exp = now + duration
+ expiration = _future(duration)
+
+ # Emulator stub: real STS signs RS256/ES384 via JWKS-published keys; we
+ # HMAC-sign so the token is self-contained and parseable but not
+ # publicly verifiable. Header reports HS256 to stay honest about the
+ # signature. Workloads that only inspect claims work; workloads that
+ # verify against AWS JWKS are not in scope for the emulator.
+ header = {"alg": "HS256", "typ": "JWT"}
+ payload = {
+ "sub": f"arn:aws:iam::{get_account_id()}:root",
+ "aud": audiences if len(audiences) > 1 else audiences[0],
+ "iss": "https://sts.amazonaws.com",
+ "iat": now,
+ "exp": exp,
+ }
+
+ def _b64url(data: bytes) -> str:
+ return base64.urlsafe_b64encode(data).rstrip(b"=").decode()
+
+ h = _b64url(json.dumps(header, separators=(",", ":")).encode())
+ p = _b64url(json.dumps(payload, separators=(",", ":")).encode())
+ sig = _b64url(hmac.new(b"ministack-fake-key", f"{h}.{p}".encode(), hashlib.sha256).digest())
+ token = f"{h}.{p}.{sig}"
+
+ if use_json:
+ return json_response({
+ "WebIdentityToken": token,
+ "Expiration": exp,
+ })
+ return _xml(200, "GetWebIdentityTokenResponse",
+ f"<GetWebIdentityTokenResult>"
+ f"<WebIdentityToken>{token}</WebIdentityToken>"
+ f"<Expiration>{expiration}</Expiration>"
+ f"</GetWebIdentityTokenResult>",
+ ns="sts")
+
return _error(400, "InvalidAction", f"Unknown STS action: {action}", ns="sts")
diff --git a/tests/test_sts.py b/tests/test_sts.py
index 32bc9418..5a3167eb 100644
--- a/tests/test_sts.py
+++ b/tests/test_sts.py
@@ -97,6 +97,138 @@ def test_sts_assume_role_with_web_identity(sts, iam):
assert "Expiration" in creds
+def _gwit_post(data: bytes):
+ """POST raw form-encoded body to STS GetWebIdentityToken (boto3 has no client method)."""
+ import urllib.request, urllib.error
+ endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
+ req = urllib.request.Request(
+ endpoint,
+ data=data,
+ method="POST",
+ headers={
+ "Content-Type": "application/x-www-form-urlencoded",
+ "Authorization": "AWS4-HMAC-SHA256 Credential=test/20240101/us-east-1/sts/aws4_request, SignedHeaders=host, Signature=fake",
+ },
+ )
+ try:
+ with urllib.request.urlopen(req) as r:
+ return r.status, r.read().decode()
+ except urllib.error.HTTPError as e:
+ return e.code, e.read().decode()
+
+
+def _b64url_pad(s):
+ return s + "=" * (-len(s) % 4)
+
+
+def test_sts_get_web_identity_token():
+ """GetWebIdentityToken returns a JWT with AWS-spec claims (XML protocol)."""
+ import re, base64
+ status, body = _gwit_post(
+ b"Action=GetWebIdentityToken&Audience=my-service&SigningAlgorithm=RS256&DurationSeconds=300"
+ )
+ assert status == 200
+ assert "<WebIdentityToken>" in body
+ token = re.search(r"<WebIdentityToken>(.+?)</WebIdentityToken>", body).group(1)
+ parts = token.split(".")
+ assert len(parts) == 3
+
+ header = json.loads(base64.urlsafe_b64decode(_b64url_pad(parts[0])))
+ payload = json.loads(base64.urlsafe_b64decode(_b64url_pad(parts[1])))
+
+ assert header["typ"] == "JWT"
+ # Header alg honestly reports HS256 (the actual signature algorithm used by
+ # the emulator); SigningAlgorithm in the request is validated separately.
+ assert header["alg"] == "HS256"
+ assert payload["aud"] == "my-service"
+ assert payload["iss"] == "https://sts.amazonaws.com"
+ assert "sub" in payload
+ assert "exp" in payload
+ assert payload["exp"] - payload["iat"] == 300
+
+
+def test_sts_get_web_identity_token_json_protocol():
+ """JSON protocol returns int-epoch Expiration per ministack convention."""
+ import urllib.request, urllib.error
+ endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
+ req = urllib.request.Request(
+ endpoint,
+ data=json.dumps({"Audience": "x", "SigningAlgorithm": "RS256"}).encode(),
+ method="POST",
+ headers={
+ "Content-Type": "application/x-amz-json-1.1",
+ "X-Amz-Target": "AWSSecurityTokenServiceV20110615.GetWebIdentityToken",
+ "Authorization": "AWS4-HMAC-SHA256 Credential=test/20240101/us-east-1/sts/aws4_request, SignedHeaders=host, Signature=fake",
+ },
+ )
+ with urllib.request.urlopen(req) as r:
+ assert r.status == 200
+ data = json.loads(r.read())
+ assert "WebIdentityToken" in data
+ assert isinstance(data["Expiration"], int)
+
+
+def test_sts_get_web_identity_token_es384():
+ """ES384 is also a valid SigningAlgorithm value."""
+ status, body = _gwit_post(b"Action=GetWebIdentityToken&Audience=x&SigningAlgorithm=ES384")
+ assert status == 200
+
+
+def test_sts_get_web_identity_token_multiple_audiences():
+ """Audience.member.N produces aud as a list when multiple."""
+ import re, base64
+ status, body = _gwit_post(
+ b"Action=GetWebIdentityToken&SigningAlgorithm=RS256"
+ b"&Audience.member.1=alpha&Audience.member.2=beta"
+ )
+ assert status == 200
+ token = re.search(r"<WebIdentityToken>(.+?)</WebIdentityToken>", body).group(1)
+ payload = json.loads(base64.urlsafe_b64decode(_b64url_pad(token.split(".")[1])))
+ assert payload["aud"] == ["alpha", "beta"]
+
+
+def test_sts_get_web_identity_token_missing_signing_algorithm():
+ status, body = _gwit_post(b"Action=GetWebIdentityToken&Audience=x")
+ assert status == 400
+ assert "MissingParameter" in body
+ assert "SigningAlgorithm" in body
+
+
+def test_sts_get_web_identity_token_invalid_signing_algorithm():
+ status, body = _gwit_post(b"Action=GetWebIdentityToken&Audience=x&SigningAlgorithm=HS256")
+ assert status == 400
+ assert "ValidationError" in body
+
+
+def test_sts_get_web_identity_token_missing_audience():
+ status, body = _gwit_post(b"Action=GetWebIdentityToken&SigningAlgorithm=RS256")
+ assert status == 400
+ assert "MissingParameter" in body
+ assert "Audience" in body
+
+
+def test_sts_get_web_identity_token_too_many_audiences():
+ audiences = "&".join(f"Audience.member.{i}=a{i}" for i in range(1, 12))
+ data = f"Action=GetWebIdentityToken&SigningAlgorithm=RS256&{audiences}".encode()
+ status, body = _gwit_post(data)
+ assert status == 400
+ assert "ValidationError" in body
+
+
+def test_sts_get_web_identity_token_duration_too_short():
+ status, body = _gwit_post(
+ b"Action=GetWebIdentityToken&Audience=x&SigningAlgorithm=RS256&DurationSeconds=10"
+ )
+ assert status == 400
+ assert "ValidationError" in body
+
+
+def test_sts_get_web_identity_token_duration_too_long():
+ status, body = _gwit_post(
+ b"Action=GetWebIdentityToken&Audience=x&SigningAlgorithm=RS256&DurationSeconds=99999"
+ )
+ assert status == 400
+ assert "ValidationError" in body
def test_get_caller_identity_reflects_assumed_role(sts_as_role):
"""GetCallerIdentity called with assumed-role creds must return the role ARN, not root."""
identity = sts_as_role("arn:aws:iam::000000000000:role/MyTestRole", "caller-identity-session").get_caller_identity()