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; 023 024/** 025 * Stable subject identifier derived from a persistent NameID. Applications key an account by 026 * the pair (IdP connection ID, this subject key); this value alone is not a tenant namespace. 027 * 028 * @since 1.0.0 029 */ 030@Immutable 031public final class SamlSubjectKey { 032 private final @NonNull String stableString; 033 034 private SamlSubjectKey(@NonNull String stableString) { this.stableString = stableString; } 035 036 static @NonNull SamlSubjectKey fromPersistentNameId(@NonNull SamlNameId nameId) { 037 if (!nameId.persistent()) throw new IllegalArgumentException("NameID is not persistent"); 038 StringBuilder encoded = new StringBuilder("saml-nameid-v1:"); 039 add(encoded, nameId.rawFormat()); 040 add(encoded, nameId.getValue()); 041 add(encoded, nameId.rawNameQualifier()); 042 add(encoded, nameId.rawSpNameQualifier()); 043 if (nameId.rawSpProvidedId() != null) add(encoded, nameId.rawSpProvidedId()); 044 return new SamlSubjectKey(encoded.toString()); 045 } 046 047 static @NonNull SamlSubjectKey fromScopedIdentifier(@NonNull String kind, @NonNull String value) { 048 StringBuilder encoded = new StringBuilder("saml-scoped-id-v1:"); 049 add(encoded, kind); 050 add(encoded, value); 051 return new SamlSubjectKey(encoded.toString()); 052 } 053 054 private static void add(@NonNull StringBuilder builder, @Nullable String value) { 055 if (value == null) builder.append("-1:"); 056 else builder.append(value.length()).append(':').append(value); 057 } 058 059 /** 060 * Returns a length-prefixed stable encoding. Treat this as personal data. 061 * 062 * @return the stable subject key 063 * @since 1.0.0 064 */ 065 public @NonNull String toStableString() { return stableString; } 066 067 /** 068 * Redacts the subject key. 069 * 070 * @return redacted description 071 * @since 1.0.0 072 */ 073 @Override public @NonNull String toString() { return "SamlSubjectKey{<redacted>}"; } 074}