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 */
016package com.revetsec.saml;
017
018import org.jspecify.annotations.NonNull;
019import org.jspecify.annotations.Nullable;
020import javax.annotation.concurrent.Immutable;
021import java.net.URI;
022import java.util.Map;
023
024/**
025 * A prepared browser form for a SAML HTTP-POST authentication or logout message. Render only over HTTPS.
026 * Retain browser-bound pending state before initiating a flow; a pending cookie needed on a cross-site
027 * POST callback requires Secure, HttpOnly and SameSite=None.
028 *
029 * @since 1.0.0
030 */
031@Immutable
032public final class SamlPostForm {
033    private final @NonNull URI action;
034    private final @NonNull Map<@NonNull String, @NonNull String> fields;
035
036    SamlPostForm(@NonNull URI action, @NonNull String request, @NonNull String relayState) {
037        this(action, "SAMLRequest", request, relayState);
038    }
039
040    SamlPostForm(@NonNull URI action, @NonNull String field, @NonNull String message,
041            @Nullable String relayState) {
042        this.action = action;
043        this.fields = relayState == null ? Map.of(field, message)
044                : Map.of(field, message, "RelayState", relayState);
045    }
046
047    /**
048     * Returns the approved IdP form action.
049     *
050     * @return HTTPS action
051     * @since 1.0.0
052     */
053    public @NonNull URI getAction() { return action; }
054    /**
055     * Returns the form fields for framework rendering.
056     *
057     * @return immutable field map
058     * @since 1.0.0
059     */
060    public @NonNull Map<@NonNull String, @NonNull String> getFields() { return fields; }
061    /**
062     * Returns response headers for a transient form page.
063     *
064     * @return immutable headers
065     * @since 1.0.0
066     */
067    public @NonNull Map<@NonNull String, @NonNull String> getHeaders() {
068        return Map.of("Cache-Control", "no-store", "Pragma", "no-cache",
069                "Referrer-Policy", "no-referrer", "Content-Type", "text/html; charset=UTF-8",
070                "X-Content-Type-Options", "nosniff");
071    }
072    /**
073     * Renders an escaped HTML form. A supplied CSP nonce adds automatic submission; otherwise the
074     * page shows a submit button. The caller sets its own Content-Security-Policy header.
075     *
076     * @param cspNonce validated application-generated nonce, or null for manual submission
077     * @return complete HTML document
078     * @since 1.0.0
079     */
080    public @NonNull String toHtml(@Nullable String cspNonce) {
081        if (cspNonce != null && !cspNonce.matches("[A-Za-z0-9_+/-]{16,128}={0,2}"))
082            throw new IllegalArgumentException("Invalid CSP nonce");
083        StringBuilder html = new StringBuilder(1024);
084        html.append("<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">")
085                .append("<title>Continue</title></head><body>")
086                .append("<form id=\"saml-post-form\" method=\"post\" action=\"")
087                .append(escape(action.toASCIIString()))
088                .append("\" autocomplete=\"off\">");
089        for (Map.Entry<String, String> field : fields.entrySet())
090            html.append("<input type=\"hidden\" name=\"").append(escape(field.getKey()))
091                    .append("\" value=\"").append(escape(field.getValue())).append("\">");
092        html.append("<noscript><button type=\"submit\">Continue</button></noscript>")
093                .append("</form>");
094        if (cspNonce != null) html.append("<script nonce=\"").append(cspNonce)
095                .append("\">document.forms[0].submit();</script>");
096        else html.append("<button type=\"submit\" form=\"saml-post-form\">Continue</button>");
097        html.append("</body></html>");
098        return html.toString();
099    }
100
101    private static @NonNull String escape(@NonNull String value) {
102        return value.replace("&", "&amp;").replace("\"", "&quot;")
103                .replace("<", "&lt;").replace(">", "&gt;").replace("'", "&#39;");
104    }
105
106    /**
107     * Redacts request values.
108     *
109     * @return redacted description
110     * @since 1.0.0
111     */
112    @Override public @NonNull String toString() { return "SamlPostForm{<redacted>}"; }
113}