public void TestCall_retrieved()
        {
            BuildConfiguration buildConfiguration =
                MakeFakeBuildConfiguration(
                    new List <CredentialRetriever>
            {
                Maybe.Empty <Credential>,
                () => Maybe.Of(Credential.From("baseusername", "basepassword"))
            },
                    new List <CredentialRetriever>
            {
                () => Maybe.Of(Credential.From("targetusername", "targetpassword")),
                () => Maybe.Of(Credential.From("ignored", "ignored"))
            });

            Assert.AreEqual(
                Credential.From("baseusername", "basepassword"),
                RetrieveRegistryCredentialsStep.ForBaseImage(
                    buildConfiguration,
                    ProgressEventDispatcher.NewRoot(mockEventHandlers, "ignored", 1).NewChildProducer())
                .Call());
            Assert.AreEqual(
                Credential.From("targetusername", "targetpassword"),
                RetrieveRegistryCredentialsStep.ForTargetImage(
                    buildConfiguration,
                    ProgressEventDispatcher.NewRoot(mockEventHandlers, "ignored", 1).NewChildProducer())
                .Call());
        }
        public void IstAuthenticationUrl_oauth2()
        {
            Credential credential = Credential.From("<token>", "oauth2_token");

            Assert.AreEqual(
                new Uri("https://somerealm"),
                registryAuthenticator.GetAuthenticationUrl(credential, "scope"));
        }
        public void TestAuthRequestParameters_oauth2()
        {
            Credential credential = Credential.From("<token>", "oauth2_access_token");

            Assert.AreEqual(
                "service=someservice&scope=repository:someimage:scope"
                + "&client_id=fib.da031fe481a93ac107a95a96462358f9"
                + "&grant_type=refresh_token&refresh_token=oauth2_access_token",
                registryAuthenticator.GetAuthRequestParameters(credential, "scope"));
        }
Example #4
0
        public void TestCredentialsOAuth2RefreshToken()
        {
            Credential oauth2Credential = Credential.From("<token>", "eyJhbGciOi...3gw");

            Assert.IsTrue(
                oauth2Credential.IsOAuth2RefreshToken(),
                "Credential should be an auth2 token when username is <token>");
            Assert.AreEqual(
                "eyJhbGciOi...3gw",
                oauth2Credential.GetPassword(),
                "OAuth2 token credential should take password as refresh token");
        }
Example #5
0
        public void TestGetters()
        {
            RegistryImage image =
                RegistryImage.Named("registry/image")
                .AddCredentialRetriever(mockCredentialRetriever)
                .AddCredential("username", "password");

            Assert.AreEqual(2, image.GetCredentialRetrievers().Count);
            Assert.AreSame(mockCredentialRetriever, image.GetCredentialRetrievers()[0]);
            Assert.AreEqual(
                Credential.From("username", "password"),
                image.GetCredentialRetrievers()[1].Retrieve().Get());
        }
Example #6
0
        /// <summary>
        /// Creates a new Credential object from a Kinvey user login/create request, and saves the it in the Credential Store.
        /// </summary>
        /// <returns>The store credential.</returns>
        /// <param name="response">Response.</param>
        /// <param name="userId">User _id.</param>
        /// <param name="ssoGroupKey">SSO Group Key.</param>
        /// <param name="deviceID">Device Id.</param>
        public Credential CreateAndStoreCredential(KinveyAuthResponse response, string userId, string ssoGroupKey, string deviceID)
        {
            Credential newCredential = Credential.From(response);

            newCredential.DeviceID = deviceID;
            if (userId != null && credentialStore != null)
            {
                var oldCred = credentialStore.Load(userId, ssoGroupKey);
                newCredential.MICClientID = oldCred?.MICClientID;
                credentialStore.Store(userId, ssoGroupKey, newCredential);
            }
            return(newCredential);
        }
Example #7
0
        public void TestCredentialsHash()
        {
            Credential credentialA1 = Credential.From("username", "password");
            Credential credentialA2 = Credential.From("username", "password");
            Credential credentialB1 = Credential.From("", "");
            Credential credentialB2 = Credential.From("", "");

            Assert.AreEqual(credentialA1, credentialA2);
            Assert.AreEqual(credentialB1, credentialB2);
            Assert.AreNotEqual(credentialA1, credentialB1);
            Assert.AreNotEqual(credentialA1, credentialB2);

            ISet <Credential> credentialSet =
                new HashSet <Credential>(new[] { credentialA1, credentialA2, credentialB1, credentialB2 });

            CollectionAssert.AreEquivalent(new HashSet <Credential>(new[] { credentialA2, credentialB1 }), credentialSet);
        }
Example #8
0
        public async Task TestScratchAsync()
        {
            ImageReference targetImageReference =
                ImageReference.Of("localhost:5002", "fibdotnet-core", "basic-scratch");
            await FibContainerBuilder.FromScratch()
            .ContainerizeAsync(
                Containerizer.To(
                    RegistryImage.Named(targetImageReference)
                    .AddCredentialRetriever(
                        () => Maybe.Of(Credential.From("username", "password"))))
                .SetAllowInsecureRegistries(true)).ConfigureAwait(false);

            // Check that resulting image has no layers
            localRegistry.Pull(targetImageReference.ToString());
            string inspectOutput = new Command("docker", "inspect", targetImageReference.ToString()).Run();

            Assert.That(inspectOutput, Does.Not.Contain("\"Layers\": ["), "docker inspect output contained layers: " + inspectOutput);
        }
        /**
         * Retrieves credentials for a registry alias from a {@link DockerConfig}.
         *
         * @param dockerConfig the {@link DockerConfig} to retrieve from
         * @param logger a consumer for handling log events
         * @return the retrieved credentials, or {@code Optional#empty} if none are found
         */

        public Maybe <Credential> Retrieve(IDockerConfig dockerConfig, Action <LogEvent> logger)
        {
            logger = logger ?? throw new ArgumentNullException(nameof(logger));
            foreach (string registryAlias in RegistryAliasGroup.GetAliasesGroup(registry))
            {
                // First, tries to find defined auth.
                string auth = dockerConfig.GetAuthFor(registryAlias);
                if (auth != null)
                {
                    // 'auth' is a basic authentication token that should be parsed back into credentials
                    string usernameColonPassword = Encoding.UTF8.GetString(Convert.FromBase64String(auth));
                    int    colonIndex            = usernameColonPassword.IndexOf(":", StringComparison.Ordinal);
                    string username = usernameColonPassword.Substring(0, colonIndex);

                    string password = usernameColonPassword.Substring(colonIndex + 1);
                    return(Maybe.Of(Credential.From(username, password)));
                }

                // Then, tries to use a defined credHelpers credential helper.
                IDockerCredentialHelper dockerCredentialHelper =
                    dockerConfig.GetCredentialHelperFor(registryAlias);
                if (dockerCredentialHelper != null)
                {
                    try
                    {
                        // Tries with the given registry alias (may be the original registry).
                        return(Maybe.Of(dockerCredentialHelper.Retrieve()));
                    }
                    catch (Exception ex) when(ex is IOException || ex is CredentialHelperUnhandledServerUrlException || ex is CredentialHelperNotFoundException)
                    {
                        // Warns the user that the specified credential helper cannot be used.
                        if (ex.Message != null)
                        {
                            logger(LogEvent.Warn(ex.Message));
                            if (ex.InnerException?.Message != null)
                            {
                                logger(LogEvent.Warn("  Caused by: " + ex.InnerException.Message));
                            }
                        }
                    }
                }
            }
            return(Maybe.Empty <Credential>());
        }
Example #10
0
        public async Task TestBasic_HelloWorldAsync()
        {
            ImageReference targetImageReference =
                ImageReference.Of("localhost:5002", "fibdotnet-core", "basic-helloworld");
            FibContainer fibContainer =
                await FibContainerBuilder.From("busybox")
                .SetEntrypoint("echo", "Hello World")
                .ContainerizeAsync(
                    Containerizer.To(
                        RegistryImage.Named(targetImageReference)
                        .AddCredentialRetriever(
                            () => Maybe.Of(Credential.From("username", "password"))))
                    .SetAllowInsecureRegistries(true)
                    .AddEventHandler <IFibEvent>(e => TestContext.Out.WriteLine(e))).ConfigureAwait(false);

            Assert.AreEqual("Hello World\n", PullAndRunBuiltImage(targetImageReference.ToString()));
            Assert.AreEqual(
                "Hello World\n",
                PullAndRunBuiltImage(
                    targetImageReference.WithTag(fibContainer.GetDigest().ToString()).ToString()));
        }
        public void TestBuilder()
        {
            const string  expectedBaseImageServerUrl         = "someserver";
            const string  expectedBaseImageName              = "baseimage";
            const string  expectedBaseImageTag               = "baseimagetag";
            const string  expectedTargetServerUrl            = "someotherserver";
            const string  expectedTargetImageName            = "targetimage";
            const string  expectedTargetTag                  = "targettag";
            ISet <string> additionalTargetImageTags          = ImmutableHashSet.Create("tag1", "tag2", "tag3");
            ISet <string> expectedTargetImageTags            = ImmutableHashSet.Create("targettag", "tag1", "tag2", "tag3");
            IList <CredentialRetriever> credentialRetrievers =
                new List <CredentialRetriever> {
                () => Maybe.Of(Credential.From("username", "password"))
            };
            Instant        expectedCreationTime                     = Instant.FromUnixTimeSeconds(10000);
            IList <string> expectedEntrypoint                       = new[] { "some", "entrypoint" };
            IList <string> expectedProgramArguments                 = new[] { "arg1", "arg2" };
            IDictionary <string, string> expectedEnvironment        = ImmutableDic.Of("key", "value");
            ImmutableHashSet <Port>      expectedExposedPorts       = ImmutableHashSet.Create(Port.Tcp(1000), Port.Tcp(2000));
            IDictionary <string, string> expectedLabels             = ImmutableDic.Of("key1", "value1", "key2", "value2");
            const ManifestFormat         expectedTargetFormat       = ManifestFormat.OCI;
            SystemPath expectedApplicationLayersCacheDirectory      = Paths.Get("application/layers");
            SystemPath expectedBaseImageLayersCacheDirectory        = Paths.Get("base/image/layers");
            IList <ILayerConfiguration> expectedLayerConfigurations =
                new List <ILayerConfiguration> {
                LayerConfiguration.CreateBuilder()
                .AddEntry(Paths.Get("sourceFile"), AbsoluteUnixPath.Get("/path/in/container"))
                .Build()
            };
            const string expectedCreatedBy = "createdBy";

            ImageConfiguration baseImageConfiguration =
                ImageConfiguration.CreateBuilder(
                    ImageReference.Of(
                        expectedBaseImageServerUrl, expectedBaseImageName, expectedBaseImageTag))
                .Build();
            ImageConfiguration targetImageConfiguration =
                ImageConfiguration.CreateBuilder(
                    ImageReference.Of(
                        expectedTargetServerUrl, expectedTargetImageName, expectedTargetTag))
                .SetCredentialRetrievers(credentialRetrievers)
                .Build();
            ContainerConfiguration containerConfiguration =
                ContainerConfiguration.CreateBuilder()
                .SetCreationTime(expectedCreationTime)
                .SetEntrypoint(expectedEntrypoint)
                .SetProgramArguments(expectedProgramArguments)
                .SetEnvironment(expectedEnvironment)
                .SetExposedPorts(expectedExposedPorts)
                .SetLabels(expectedLabels)
                .Build();

            BuildConfiguration.Builder buildConfigurationBuilder =
                BuildConfiguration.CreateBuilder()
                .SetBaseImageConfiguration(baseImageConfiguration)
                .SetTargetImageConfiguration(targetImageConfiguration)
                .SetAdditionalTargetImageTags(additionalTargetImageTags)
                .SetContainerConfiguration(containerConfiguration)
                .SetApplicationLayersCacheDirectory(expectedApplicationLayersCacheDirectory)
                .SetBaseImageLayersCacheDirectory(expectedBaseImageLayersCacheDirectory)
                .SetTargetFormat(ImageFormat.OCI)
                .SetAllowInsecureRegistries(true)
                .SetLayerConfigurations(expectedLayerConfigurations)
                .SetToolName(expectedCreatedBy);
            BuildConfiguration buildConfiguration = buildConfigurationBuilder.Build();

            Assert.IsNotNull(buildConfiguration.GetContainerConfiguration());
            Assert.AreEqual(
                expectedCreationTime, buildConfiguration.GetContainerConfiguration().GetCreationTime());
            Assert.AreEqual(
                expectedBaseImageServerUrl,
                buildConfiguration.GetBaseImageConfiguration().GetImageRegistry());
            Assert.AreEqual(
                expectedBaseImageName, buildConfiguration.GetBaseImageConfiguration().GetImageRepository());
            Assert.AreEqual(
                expectedBaseImageTag, buildConfiguration.GetBaseImageConfiguration().GetImageTag());
            Assert.AreEqual(
                expectedTargetServerUrl,
                buildConfiguration.GetTargetImageConfiguration().GetImageRegistry());
            Assert.AreEqual(
                expectedTargetImageName,
                buildConfiguration.GetTargetImageConfiguration().GetImageRepository());
            Assert.AreEqual(
                expectedTargetTag, buildConfiguration.GetTargetImageConfiguration().GetImageTag());
            Assert.AreEqual(expectedTargetImageTags, buildConfiguration.GetAllTargetImageTags());
            Assert.AreEqual(
                Credential.From("username", "password"),
                buildConfiguration
                .GetTargetImageConfiguration()
                .GetCredentialRetrievers()
                [0]
                .Retrieve()
                .OrElseThrow(() => new AssertionException("")));
            Assert.AreEqual(
                expectedProgramArguments,
                buildConfiguration.GetContainerConfiguration().GetProgramArguments());
            Assert.AreEqual(
                expectedEnvironment, buildConfiguration.GetContainerConfiguration().GetEnvironmentMap());
            Assert.AreEqual(
                expectedExposedPorts, buildConfiguration.GetContainerConfiguration().GetExposedPorts());
            Assert.AreEqual(expectedLabels, buildConfiguration.GetContainerConfiguration().GetLabels());
            Assert.AreEqual(expectedTargetFormat, buildConfiguration.GetTargetFormat());
            Assert.AreEqual(
                expectedApplicationLayersCacheDirectory,
                buildConfigurationBuilder.GetApplicationLayersCacheDirectory());
            Assert.AreEqual(
                expectedBaseImageLayersCacheDirectory,
                buildConfigurationBuilder.GetBaseImageLayersCacheDirectory());
            Assert.IsTrue(buildConfiguration.GetAllowInsecureRegistries());
            Assert.AreEqual(expectedLayerConfigurations, buildConfiguration.GetLayerConfigurations());
            Assert.AreEqual(
                expectedEntrypoint, buildConfiguration.GetContainerConfiguration().GetEntrypoint());
            Assert.AreEqual(expectedCreatedBy, buildConfiguration.GetToolName());
        }
Example #12
0
        /**
         * Calls the credential helper CLI in the form:
         *
         * <pre>{@code
         * echo -n <server Uri> | docker-credential-<credential helper suffix> get
         * }</pre>
         *
         * @return the Docker credentials by calling the corresponding CLI
         * @throws IOException if writing/reading process input/output fails
         * @throws CredentialHelperUnhandledServerUrlException if no credentials could be found for the
         *     corresponding server
         * @throws CredentialHelperNotFoundException if the credential helper CLI doesn't exist
         */
        public Credential Retrieve()
        {
            try
            {
                IProcess process = new ProcessBuilder(credentialHelper, "get").Start();
                using (Stream processStdin = process.GetOutputStream())
                {
                    byte[] bytes = Encoding.UTF8.GetBytes(registry);
                    processStdin.Write(bytes, 0, bytes.Length);
                }

                using (StreamReader processStdoutReader =
                           new StreamReader(process.GetInputStream(), Encoding.UTF8))
                {
                    string output = processStdoutReader.ReadToEnd();

                    // Throws an exception if the credential store does not have credentials for serverUrl.
                    if (output.Contains("credentials not found in native keychain"))
                    {
                        throw new CredentialHelperUnhandledServerUrlException(
                                  credentialHelper, registry, output);
                    }
                    if (string.IsNullOrEmpty(output))
                    {
                        ThrowUnhandledUrlException(process);
                    }

                    try
                    {
                        DockerCredentialsTemplate dockerCredentials =
                            JsonTemplateMapper.ReadJson <DockerCredentialsTemplate>(output);
                        if (string.IsNullOrEmpty(dockerCredentials.Username) ||
                            string.IsNullOrEmpty(dockerCredentials.Secret))
                        {
                            throw new CredentialHelperUnhandledServerUrlException(
                                      credentialHelper, registry, output);
                        }

                        return(Credential.From(dockerCredentials.Username, dockerCredentials.Secret));
                    }
                    catch (JsonException ex)
                    {
                        throw new CredentialHelperUnhandledServerUrlException(
                                  credentialHelper, registry, output, ex);
                    }
                }
            }
            catch (Win32Exception ex) when(ex.NativeErrorCode == Win32ErrorCodes.FileNotFound)
            {
                if (ex.Message == null)
                {
                    throw;
                }

                // Checks if the failure is due to a nonexistent credential helper CLI.
                if (ex.Message.Contains("No such file or directory") ||
                    ex.Message.Contains("cannot find the file"))
                {
                    throw new CredentialHelperNotFoundException(credentialHelper, ex);
                }

                throw;
            }
        }
        public void IsOAuth2Auth_basicAuth()
        {
            Credential credential = Credential.From("name", "password");

            Assert.IsFalse(RegistryAuthenticator.IsOAuth2Auth(credential));
        }
        public void IsOAuth2Auth_oauth2()
        {
            Credential credential = Credential.From("<token>", "oauth2_token");

            Assert.IsTrue(RegistryAuthenticator.IsOAuth2Auth(credential));
        }
        public void TestToBuildConfiguration()
        {
            RegistryImage targetImage =
                RegistryImage.Named(ImageReference.Of("gcr.io", "my-project/my-app", null))
                .AddCredential("username", "password");
            IContainerizer containerizer =
                Containerizer.To(targetImage)
                .SetBaseImageLayersCache(Paths.Get("base/image/layers"))
                .SetApplicationLayersCache(Paths.Get("application/layers"))
                .AddEventHandler(mockFibEventConsumer);

            RegistryImage baseImage =
                RegistryImage.Named("base/image").AddCredentialRetriever(mockCredentialRetriever);
            FibContainerBuilder fibContainerBuilder =
                new FibContainerBuilder(baseImage, buildConfigurationBuilder)
                .SetLayers(new[] { mockLayerConfiguration1, mockLayerConfiguration2 });
            BuildConfiguration buildConfiguration =
                fibContainerBuilder.ToBuildConfiguration(
                    containerizer);

            Assert.AreEqual(
                buildConfigurationBuilder.Build().GetContainerConfiguration(),
                buildConfiguration.GetContainerConfiguration());

            Assert.AreEqual(
                "base/image", buildConfiguration.GetBaseImageConfiguration().GetImage().ToString());
            Assert.AreEqual(
                new[] { mockCredentialRetriever },
                buildConfiguration.GetBaseImageConfiguration().GetCredentialRetrievers());

            Assert.AreEqual(
                "gcr.io/my-project/my-app",
                buildConfiguration.GetTargetImageConfiguration().GetImage().ToString());
            Assert.AreEqual(
                1, buildConfiguration.GetTargetImageConfiguration().GetCredentialRetrievers().Length);
            Assert.AreEqual(
                Credential.From("username", "password"),
                buildConfiguration
                .GetTargetImageConfiguration()
                .GetCredentialRetrievers()
                [0]
                .Retrieve()
                .OrElseThrow(() => new AssertionException("")));

            Assert.AreEqual(ImmutableHashSet.Create("latest"), buildConfiguration.GetAllTargetImageTags());

            Assert.AreEqual(
                new[] { mockLayerConfiguration1, mockLayerConfiguration2 },
                buildConfiguration.GetLayerConfigurations());

            buildConfiguration.GetEventHandlers().Dispatch(mockFibEvent);
            Mock.Get(mockFibEventConsumer).Verify(m => m(mockFibEvent));

            Assert.AreEqual("fibdotnet-core", buildConfiguration.GetToolName());

            Assert.AreEqual(ManifestFormat.V22, buildConfiguration.GetTargetFormat());

            Assert.AreEqual("fibdotnet-core", buildConfiguration.GetToolName());

            // Changes fibContainerBuilder.
            buildConfiguration =
                fibContainerBuilder
                .SetFormat(ImageFormat.OCI)
                .ToBuildConfiguration(
                    containerizer
                    .WithAdditionalTag("tag1")
                    .WithAdditionalTag("tag2")
                    .SetToolName("toolName"));
            Assert.AreEqual(ManifestFormat.OCI, buildConfiguration.GetTargetFormat());
            Assert.AreEqual(
                ImmutableHashSet.Create("latest", "tag1", "tag2"), buildConfiguration.GetAllTargetImageTags());
            Assert.AreEqual("toolName", buildConfiguration.GetToolName());
        }