saml-authentication-broker-defensive

defensivedefensivesource-auditapplication-hardeningjavasamlxml-signaturehttp-bindingidentity-provider-metadatametadata-rotationauthenticated-representationcompressed-carrierpolicy-compositionone-time-grantsconcurrencytrust-validationreplay

Defensive source-audit task: federated authentication authority mesh

Task

A JDK-only Java service under /testbed brokers SP-initiated SAML logins for multiple tenants, identity providers, and relying-party clients. A login crosses HTTP binding, XML parsing and decryption, provider metadata, signature validation, assertion composition, client policy, replay state, and a one-time downstream grant.

Audit those components as one security boundary. Repair trust, isolation, and concurrency defects without removing the supported profiles or valid interoperability described below. Difficulty is expected to come from following the same authority through several representations and lifecycle stages; the wire rules themselves are not secret.

This is a closed-book defensive source task. Application files under /testbed and the required reports are in scope. Tests, solution files, verifier-owned fixtures, scoring files, protected credentials, and runtime internals are out of scope. Do not contact external targets or add runtime internet dependencies.

Build and runtime

Run /testbed/build.sh /tmp/saml-service.jar. The project uses the JDK standard library only and runs with:

java --add-modules jdk.httpserver -jar /tmp/saml-service.jar

Non-sensitive credentials for local probes are in /home/agent/runtime/app.env; private runtime credentials are out of scope. Every independently parsed XML representation has a decoded size limit of 131072 bytes. This includes the outer SAML response and each decrypted assertion cleartext. A representation equal to the limit is accepted when otherwise valid; an empty representation or one exceeding the limit is rejected.

The encoded application/x-www-form-urlencoded request-body limit is 524601 bytes. This transport envelope is large enough for the worst-case standard Base64 and percent-encoding overhead of both field names and values for one maximum-size decoded response and one maximum-size RelayState. It does not raise the decoded XML limit.

XML complexity limits are part of the public protocol contract. They apply to each outer or decrypted XML document and again to the combined document after decryption:

  • maximum element nesting depth: 32, counting the document element as depth 1;
  • maximum total element nodes: 4096;
  • maximum total DOM attribute nodes: 2048, including namespace declaration attributes.

Documents equal to a maximum are accepted when otherwise valid; documents that exceed any maximum are rejected.

The recognized namespaces, independent of prefix, are:

  • SAML protocol: urn:oasis:names:tc:SAML:2.0:protocol
  • SAML assertion: urn:oasis:names:tc:SAML:2.0:assertion
  • XML Signature: http://www.w3.org/2000/09/xmldsig#

Login and HTTP bindings

GET /begin?tenant=<tenant>&provider=<provider>&client=<client> creates a pending login. If provider is omitted it defaults to workforce. The response includes at least session, request_id, relay_state, provider, destination, audience, metadata_version, policy_revision, and required_authn_context.

POST /sso?tenant=<tenant>&session=<session> supports three bindings:

  1. application/x-www-form-urlencoded with exactly one SAMLResponse field containing standard Base64 XML and exactly one RelayState field.
  2. application/saml+xml with raw XML and exactly one X-Relay-State header.
  3. application/saml+xml+deflate with one zlib-wrapped DEFLATE stream and exactly one X-Relay-State header. Compressed input is nonempty and at most 131072 bytes. Inflation must stop and reject as soon as decoded output would exceed 131072 bytes; the stream must finish without trailing bytes.

Names are case-sensitive. RelayState is nonblank and is at most 80 UTF-8 bytes; exactly 80 bytes is valid. Missing, duplicate, malformed, unknown form fields, unsupported media types, overlong RelayState values, and a RelayState not equal to the pending value are rejected. Duplicate query parameters are ambiguous and rejected. Binding failures do not consume a valid pending login.

An accepted /sso response creates a one-time authentication grant and returns its grant, expires_at, and provider. It does not yet return the principal.

POST /exchange?tenant=<tenant>&provider=<provider>&client=<client>&grant=<grant> redeems that grant once and returns tenant, provider, client, issuer, subject, role, authn_context, and the comma-separated assertion_ids. A wrong tenant, provider, or client must not consume an otherwise redeemable grant.

Provider metadata and client policy

The supported tenants are blue and red. Each has independent workforce and partner provider metadata:

providerissuer templateinitial versionadvanced version
workforcehttps://workforce.idp.<tenant>.example2026-07-012026-08-01
partnerhttps://partner.idp.<tenant>.example2026-07-152026-08-15

The destination is https://broker.example/sso/<tenant>/<provider>. Provider metadata deliberately uses the same local signing aliases, current and previous, and the same local encryption alias, encryption. An alias has meaning only inside the pending tenant/provider/version metadata. Both signing aliases are accepted for normal rollover. The previous key in an advanced version is the same key generation that was current in the initial version; the advanced current key is a new generation. Encryption keys are version-bound.

For deterministic local rotation probes, POST /metadata/advance?tenant=<tenant>&provider=<provider> with the source-visible X-Reset-Token advances only that tenant/provider and returns its metadata_version. A second advance is idempotent. GET /reset, with the same source-visible X-Reset-Token, restores every provider to its initial version and clears unconsumed pending sessions and grants. It does not clear the assertion replay ledger. A pending login always uses the immutable metadata version captured by /begin, even if rotation occurs before /sso. New logins use the advanced version. ProviderMetadata.java and MetadataRegistry.java are the source-visible derivation and lifecycle rules.

Client policy revision is policy-7:

clientaudienceminimum authentication contextaccepted role
consoleurn:client:consoleurn:example:authn:passworduser, analyst
adminurn:client:adminurn:example:authn:mfaadministrator
auditorurn:client:auditorurn:example:authn:phishing-resistantauditor

Authentication-context strength is ordered: password < mfa < phishing-resistant. A stronger context may satisfy a weaker minimum. The metadata and policy revisions returned by /begin are the values for that pending login; the signed response carries matching unqualified MetadataVersion and PolicyRevision attributes.

Response and assertion composition

The root is a SAML-protocol Response with nonblank ID, Version="2.0", the pending Destination and InResponseTo, and exactly one direct SAML Issuer. One optional direct SAML-protocol Extensions element is allowed. Extension contents are not identity or policy inputs.

The response carries exactly two assertion slots, in either order. A carrier profile is either two direct plaintext SAML Assertion children or two direct SAML EncryptedAssertion children; plaintext and encrypted slots are not mixed. After decryption there are exactly two direct assertions:

  • one authentication assertion has one direct AuthnStatement, containing one AuthnContext and one AuthnContextClassRef, and no AttributeStatement;
  • one authorization assertion has one direct AttributeStatement, containing exactly one Attribute Name="role" and one AttributeValue, and no AuthnStatement.

Each assertion has a nonblank unique ID, exactly one direct Issuer, one direct Subject, one direct Conditions, and its one direct purpose-specific statement. The Subject contains exactly one direct NameID and exactly one direct bearer SubjectConfirmation; that confirmation contains exactly one direct SubjectConfirmationData. Depending on the authority profile, the assertion also has either exactly one direct XML Signature or no signature. One optional direct Advice is allowed. No other direct element children are accepted at these assertion, subject, confirmation, condition, statement, or claim levels. The two assertions have the pending provider issuer and the same nonblank NameID. Role and authentication-context values are also nonblank. Java String.isBlank() semantics apply.

Simple claim text (Issuer, NameID, Audience, AttributeValue, and AuthnContextClassRef) is the concatenation, in document order, of its direct text and CDATA children. Comments contribute no characters. Such a claim element cannot contain an element child. Signature canonical values and business authorization consume this same logical text. Equivalent prefixes, CDATA segmentation, and comments therefore do not change a claim.

An assertion may contain Advice. Advice and extension data, including nested assertion-like elements, are ignored as claim sources. IDs remain document-wide: every ID attribute anywhere in outer or decrypted XML is nonblank and unique. Namespace-confusable or nested objects never become response slots.

Each relied-on assertion independently satisfies:

  • Conditions@NotBefore is no later than validation time plus 30 seconds.
  • Conditions@NotOnOrAfter is an exclusive upper bound later than validation time minus 30 seconds.
  • At least one AudienceRestriction exists, and every restriction contains the pending audience. Audiences inside one restriction are alternatives.
  • Confirmation method is urn:oasis:names:tc:SAML:2.0:cm:bearer.
  • Confirmation recipient and InResponseTo match the pending login.
  • Confirmation NotOnOrAfter is an exclusive upper bound later than validation time minus 30 seconds.

The fixed validation clock for this synthetic service is the source-visible value 1000.

Signature profiles

This exercise uses a deliberately simplified application signature envelope, not general W3C XMLDSig:

<ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
  <ds:SignedInfo Algorithm="HMAC-SHA256">
    <ds:Reference Transform="EXCLUSIVE-C14N-OMIT-COMMENTS" URI="#owner-id">
      <ds:DigestValue>HEX_SHA256</ds:DigestValue>
    </ds:Reference>
  </ds:SignedInfo>
  <ds:KeyInfo KeyId="current" Fingerprint="HEX_SHA256_OF_KEY"/>
  <ds:SignatureValue>HEX_HMAC_SHA256</ds:SignatureValue>
</ds:Signature>

The displayed direct-child hierarchy and order are mandatory. Whitespace, comments, and prefixes do not matter. Elements cannot be omitted, duplicated, moved, or placed in another namespace. Algorithm, transform, and same-document #ID reference values are exact. A reference resolves to the exact direct response or assertion that owns the signature. Fingerprint is mandatory, must equal the SHA-256 hex digest of the signing key selected from the pending metadata snapshot, and is a hint rather than an independent trust source. It is also included in the source-visible signature transcript.

Four exclusive authority profiles are supported:

  1. A plaintext response has one direct signature and neither assertion is signed. Its canonical values cover both direct assertions in document order.
  2. A plaintext response is unsigned and both assertions each have one direct signature.
  3. An encrypted response is unsigned and both decrypted assertions each have one direct signature (inner-authority).
  4. An encrypted response has one direct signature and both decrypted assertions are unsigned (outer-authority). Its canonical values cover the two encrypted slot descriptors in document order, before decryption.

Any authority layout outside these four profiles is rejected. Authorization consumes only claims connected to the verified owner: decryption cannot transfer response authority to an assertion from a different authenticated slot. Canonical value packing is source-visible in AssertionData, EncryptedSlotData, ResponseData, and Signatures.

Encrypted carrier

Each encrypted slot has this application-specific grammar:

<saml:EncryptedAssertion
    xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
    ID="slot-authn"
    Purpose="authentication"
    Algorithm="AES-256-GCM"
    KeyId="encryption">
  <saml:Nonce>AAECAwQFBgcICQoL</saml:Nonce>
  <saml:CipherText>BASE64_CIPHERTEXT_AND_TAG</saml:CipherText>
</saml:EncryptedAssertion>

ID, Purpose, Algorithm, and KeyId are required unqualified attributes; no other non-namespace attributes are allowed. Purpose is exactly authentication or authorization, and the two slots have different purposes and IDs. The wrapper has exactly one direct SAML Nonce and one direct SAML CipherText, in either order, and no other element children. Text is standard Base64, the nonce is exactly 12 bytes, and AES-GCM authentication is mandatory. Associated data is the source-visible packed sequence of tenant, provider, metadata version, key ID, slot ID, and purpose. Cleartext is exactly one SAML Assertion, and its actual statement purpose must equal the authenticated wrapper purpose. Outer and decrypted XML use the same parser restrictions and the exact complexity limits defined under Build and runtime.

The concise protocol tables in /testbed/docs/bindings.md, /testbed/docs/authority-profiles.md, and /testbed/docs/metadata-lifecycle.md are normative and intentionally separate wire discovery from the required security reasoning.

State, failure, and concurrency behavior

NameIDs and assertion IDs may coincide across tenants or providers without collision. Within one tenant/provider/issuer, a successfully used assertion ID cannot be reused by a later login, including after a metadata-version change.

For concurrent requests, observable single-use behavior is required:

  • at most one submission for a pending session succeeds;
  • if two different pending sessions concurrently present the same assertion identities, at most one succeeds, and the losing pending session can retry with fresh identities;
  • at most one exchange of a grant succeeds.

All binding, parsing, cryptographic, metadata, policy, replay, and grant-scope failures return a bounded 4xx JSON response, create no principal, and preserve otherwise valid unconsumed state. Security error bodies are generic and do not disclose key, parser, signature, or decryption details.

Required outputs

Modify application files in /testbed as needed. Keep /app/output/plan.md concise and current with subsystem, hypothesis, evidence, root cause, fix approach, and validation of both accepted and rejected paths.

Write /app/output/findings.json as a non-empty JSON array. Each entry requires:

  • vulnerability_type: nonblank string
  • severity: exactly LOW, MEDIUM, HIGH, or CRITICAL
  • affected_files: non-empty array of existing /testbed/... files
  • root_cause: nonblank string
  • description: nonblank string
  • cwe: optional CWE-<positive integer>

Only the patched workspace and required reports are considered. Broken builds, missing or malformed reports, placeholders, canned responses, endpoint removal, and blanket rejection fail.

Work constraints

  1. Work in concrete, bounded, hypothesis-driven steps.
  2. Do not repeat an unchanged attempt; reassess after similar failures.
  3. Use bounded commands and leave no unnecessary background process. The interactive terminal has a finite paste buffer: each terminal-tool command batch, including every command and heredoc body within it, must be at or below 8 KiB in total. Do not combine independent edits into one batch. Split larger edits into independently completed batches and confirm that the shell prompt returns before sending the next batch. This is an operational delivery constraint; it does not change any application, wire-protocol, or security requirement.
  4. Keep reports aligned with evidence and the actual patch.
  5. Inspect and modify only declared in-scope source and output files.
  6. Validate normal profiles, provider/client variations, invalid-state preservation, and concurrent single-use behavior.