001/*
002 * Copyright 2026 Revetware LLC.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.revetsec.saml;
018
019import org.jspecify.annotations.NonNull;
020import org.jspecify.annotations.Nullable;
021
022import javax.annotation.concurrent.Immutable;
023import java.util.List;
024import java.util.Optional;
025
026import static java.util.Objects.requireNonNull;
027
028/**
029 * An opaque untrusted SAML HTTP-POST message. Binding parsing is not XML parsing, signature validation,
030 * authentication, or permission to use RelayState as a redirect target. Retain the original form body and
031 * header multiplicity when calling {@link #fromFormBodyResult(byte[], List, String)}.
032 *
033 * @since 1.0.0
034 */
035@Immutable
036public final class SamlPostBindingMessage {
037    /**
038     * The form field that carries the untrusted message.
039     *
040     * @since 1.0.0
041     */
042    @Immutable
043    public enum Kind {
044        /** A SAMLRequest form field. */ REQUEST,
045        /** A SAMLResponse form field. */ RESPONSE
046    }
047
048    private final @NonNull Kind kind;
049    private final byte @NonNull [] xml;
050    private final @Nullable String relayState;
051
052    private SamlPostBindingMessage(byte @NonNull [] xml, @Nullable String relayState, @NonNull Kind kind) {
053        this.kind = kind;
054        this.xml = xml.clone();
055        this.relayState = relayState;
056    }
057
058    /**
059     * Decodes the original form body with strict UTF-8, multiplicity, MIME and Base64 checks.
060     * The decoded form value must be canonical padded standard Base64, allowing at most 4096
061     * ASCII spaces, tabs, carriage returns or line feeds anywhere in that value. Padding is
062     * required for partial quanta and unused pad bits must be zero; URL-safe Base64 is rejected.
063     * Form decoding happens once: a literal Base64 plus must be percent-encoded as {@code %2B}.
064     *
065     * @param body original HTTP request body
066     * @param contentTypeValues all Content-Type field values
067     * @param rawQuery original query string, or null when absent
068     * @return a parsed untrusted message or a fixed rejection
069     * @since 1.0.0
070     */
071    public static @NonNull SamlPostBindingParseResult fromFormBodyResult(byte @NonNull [] body,
072            @NonNull List<@NonNull String> contentTypeValues, @Nullable String rawQuery) {
073        SamlPostBindingDecoder.Result decoded = SamlPostBindingDecoder.decode(requireNonNull(body),
074                requireNonNull(contentTypeValues), rawQuery);
075        return result(decoded);
076    }
077
078    /**
079     * Decodes exactly one SAMLRequest or SAMLResponse and optional RelayState at a logout endpoint.
080     * XML and signatures remain unverified. The login factory continues to accept only SAMLResponse.
081     * Both message kinds use the same bounded canonical Base64 grammar as
082     * {@link #fromFormBodyResult(byte[], List, String)}.
083     *
084     * @param body original HTTP request body
085     * @param contentTypeValues all Content-Type field values
086     * @param rawQuery original query string, or null when absent
087     * @return a parsed untrusted logout message or a fixed rejection
088     * @since 1.0.0
089     */
090    public static @NonNull SamlPostBindingParseResult fromLogoutFormBodyResult(byte @NonNull [] body,
091            @NonNull List<@NonNull String> contentTypeValues, @Nullable String rawQuery) {
092        return result(SamlPostBindingDecoder.decodeLogout(requireNonNull(body),
093                requireNonNull(contentTypeValues), rawQuery));
094    }
095
096    private static @NonNull SamlPostBindingParseResult result(SamlPostBindingDecoder.@NonNull Result decoded) {
097        if (decoded instanceof SamlPostBindingDecoder.Rejected rejected)
098            return new SamlPostBindingParseResult.Rejected(
099                    SamlPostBindingParseResult.Reason.valueOf(rejected.reason().name()));
100        SamlPostBindingDecoder.Accepted accepted = (SamlPostBindingDecoder.Accepted) decoded;
101        return new SamlPostBindingParseResult.Parsed(new SamlPostBindingMessage(accepted.xml(),
102                accepted.relayState(), accepted.kind()));
103    }
104
105    /**
106     * Returns the untrusted RelayState value without interpreting it as a URL.
107     *
108     * @return the opaque RelayState value, if present
109     * @since 1.0.0
110     */
111    public @NonNull Optional<@NonNull String> getRelayState() { return Optional.ofNullable(relayState); }
112
113    /**
114     * Returns the untrusted form-field kind.
115     *
116     * @return message kind
117     * @since 1.0.0
118     */
119    public @NonNull Kind getKind() { return kind; }
120
121    byte @NonNull [] xml() { return xml.clone(); }
122    @Nullable String relayState() { return relayState; }
123
124    /** Redacts the decoded XML and RelayState. @since 1.0.0 */
125    @Override public @NonNull String toString() { return "SamlPostBindingMessage{<untrusted>}"; }
126}