using dk.nsi.seal; using dk.nsi.seal.dgwstypes; using NUnit.Framework; using SealTest.SosiGW; using System; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.ServiceModel; using System.Threading.Tasks; using System.Xml.Linq; using GW = SealTest.SosiGW; using static SealTest.SosiGW.SosiGWFacadeClient.EndpointConfiguration; using SubjectIdentifierType = dk.nsi.seal.dgwstypes.SubjectIdentifierType; using SealTest.Certificate; using static dk.nsi.seal.MessageHeaders.IdCardMessageHeader; using static dk.nsi.seal.MessageHeaders.XmlMessageHeader; using Action = dk.nsi.seal.Action; namespace SealTest.AssertionTests; public class Sosi2SamlTest { private static CertificateOces3MocesCpr MocesUser => new(); public static UserIdCard IdCard { get { var cvr = MocesUser.Cvr; const string orgName = "Test", itSystemName = "Test", givenName = "NA", surName = "NA", email = "NA", occupation = null, role = "NA", authorizationcode = null, userName = "", password = "", cpr = "0306894781"; return new UserIdCard(Configuration.SosiDgwsVersion, AuthenticationLevel.MocesTrustedUser, "https://saml.test-nemlog-in.dk/", new SystemInfo(new CareProvider(SubjectIdentifierType.medcomcvrnumber, cvr, orgName), itSystemName), new UserInfo(cpr, givenName, surName, email, occupation, role, authorizationcode), null, "nameId", userName, password); } } public static async Task LoginToGateway(IdCard idCard, X509Certificate2 userCert) { var sosiGwAssertion = idCard.GetAssertion(); var security = new GW.Security { Timestamp = new GW.Timestamp { Created = DateTimeEx.UtcNowRound - TimeSpan.FromMinutes(5) }, Assertion = sosiGwAssertion }; const string endpointAddress = "http://test1.ekstern-test.nspop.dk:8080/sosigw/service/sosigw"; await using var gwClient = new SosiGWFacadeClient(SosiGWSoapBinding, endpointAddress); var dig = (await gwClient.requestIdCardDigestForSigningAsync(security, "whatever")) .requestIdCardDigestForSigningResponse; var digestHash = SHA1.HashData(dig.DigestValue); var signature = userCert.GetRSAPrivateKey()!.SignHash(digestHash, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1); var cardRequestBody = new signIdCardRequestBody { SignatureValue = signature, KeyInfo = new GW.KeyInfo { Item = new GW.X509Data { Item = userCert.Export(X509ContentType.Cert) } } }; // The STS signed card is saved in the sosiGw cache and is used for future calls through the proxy using (new OperationContextScope(gwClient.InnerChannel)) { // Adding seal-security and dgws-header soap header OperationContext.Current.OutgoingMessageHeaders.Add(IdCardHeader(idCard)); OperationContext.Current.OutgoingMessageHeaders .Add(XmlHeader(MakeDgwsHeader(AuthenticationLevel.MocesTrustedUser.Level))); var res = (await gwClient.signIdCardAsync(null, cardRequestBody)).signIdCardResponse; if (res != signIdCardResponse.ok) { throw new Exception("Gateway logon error"); } } //Convert the GW Assertion to a dgwsType Assertion var sosiGwAssertionDocument = SerializerUtil.Serialize(sosiGwAssertion).Root; return SerializerUtil.Deserialize(sosiGwAssertionDocument, nameof(AssertionType)); } private static Header MakeDgwsHeader(int securityLevel) => new() { SecurityLevel = securityLevel, SecurityLevelSpecified = true, TimeOut = TimeOut.Item1440, TimeOutSpecified = true, Linking = new Linking { FlowID = Guid.NewGuid().ToString("D"), MessageID = Guid.NewGuid().ToString("D") }, FlowStatus = FlowStatus.flow_running, FlowStatusSpecified = true, Priority = Priority.RUTINE, RequireNonRepudiationReceipt = RequireNonRepudiationReceipt.yes }; [Test] [Ignore("SDS-7093")] public async Task GivenClientThenExchangeAssertionToDccShouldReturnToken() { await LoginToGateway(IdCard, MocesUser.Certificate); var uri = new Uri("http://test1.ekstern-test.nspop.dk:8080/decoupling"); var response = Sosi2SamlStsClient.ExchangeAssertion(uri, Action.DccSosiIboIssue, "/ststest", IdCard); Assert.False(response.IsFault); } [Test] public async Task GivenClientThenExchangeAssertionWithInvalidAudienceShouldReturnFault() { await LoginToGateway(IdCard, MocesUser.Certificate); var uri = new Uri("http://test1.ekstern-test.nspop.dk:8080/sosigw/proxy/soap-request"); var response = Sosi2SamlStsClient.ExchangeAssertion(uri, Action.DccSosiIboIssue, "Invalid audience", IdCard); Assert.True(response.IsFault); } [Test] [Ignore("SDS-7093")] public async Task GivenClientThenExchangeAssertionThroughGatewayShouldReturnToken() { await LoginToGateway(IdCard, MocesUser.Certificate); var uri = new Uri("http://test1.ekstern-test.nspop.dk:8080/sosigw/proxy/soap-request"); var wsAddressing = WsAddressing.New("http://test1.ekstern-test.nspop.dk:8080/sts/services/Sosi2OIOSaml"); var response = Sosi2SamlStsClient.ExchangeAssertion(uri, wsAddressing, "/ststest", IdCard); Assert.False(response.IsFault); } [Test] [Ignore("SDS-7093")] public async Task GivenClientThenExchangeAssertionThroughGatewayWithActionShouldReturnToken() { await LoginToGateway(IdCard, MocesUser.Certificate); var uri = new Uri("http://test1.ekstern-test.nspop.dk:8080/sosigw/proxy/soap-request"); var wsAddressing = WsAddressing.New("http://test1.ekstern-test.nspop.dk:8080/sts/services/Sosi2OIOSaml"); var response = Sosi2SamlStsClient.ExchangeAssertion(uri, Action.DccSosiIboIssue, wsAddressing, "/ststest", IdCard); Console.WriteLine(response.XAssertion.ToString(SaveOptions.DisableFormatting)); // TODO Assert.False(response.IsFault); } [Test] [Ignore("SDS-7093")] public void GivenClientThenExchangeAssertionWithDirectCallToSosi2OioSamlShouldReturnToken() { var cvr = MocesUser.Cvr; const string orgName = "Some value", itSystemName = "Some value", givenName = "Some value", surName = "Some value", email = "Some value", occupation = null, role = "Some value", authorizationcode = "KT2Z4", userName = "", password = "", cpr = "0306894781"; var idCard = new UserIdCard(Configuration.SosiDgwsVersion, AuthenticationLevel.MocesTrustedUser, "https://saml.test-nemlog-in.dk/", new SystemInfo(new CareProvider(SubjectIdentifierType.medcomcvrnumber, cvr, orgName), itSystemName), new UserInfo(cpr, givenName, surName, email, occupation, role, authorizationcode), null, "nameId", userName, password); var assertion = idCard.GetAssertion(); var signedAssertion = SealUtilities.SignAssertion(assertion, MocesUser.Certificate); idCard.Xassertion = SerializerUtil.Serialize(signedAssertion).Root; var stsSignedIdCard = SealUtilities.SignIn(idCard, "test", TestConstants.SecurityTokenServiceNewSecurityToken); var uri = new Uri("http://test1.ekstern-test.nspop.dk:8080/sts/services/Sosi2OIOSaml"); var response = Sosi2SamlStsClient.ExchangeAssertion(uri, "/ststest", stsSignedIdCard); Assert.False(response.IsFault); } }