Exemplo n.º 1
0
func TestNodeConfigTLS(t *testing.T) {
	signerCert, signerKey, signerSerial := makeSignerCert(t)
	defer os.Remove(signerCert)
	defer os.Remove(signerKey)
	defer os.Remove(signerSerial)

	configDirName := executeNodeConfig([]string{"--node=my-node", "--hostnames=example.org", "--listen=https://0.0.0.0", "--certificate-authority=" + signerCert, "--node-client-certificate-authority=" + signerCert, "--signer-cert=" + signerCert, "--signer-key=" + signerKey, "--signer-serial=" + signerSerial})
	defer os.Remove(configDirName)

	configDir, err := os.Open(configDirName)
	if err != nil {
		t.Fatalf("unable to read %v", configDirName)
	}

	fileNameSlice, err := configDir.Readdirnames(0)
	if err != nil {
		t.Fatalf("unable to read %v", configDirName)
	}
	filenames := util.NewStringSet(fileNameSlice...)

	expectedNames := util.NewStringSet("master-client.crt", "master-client.key", "server.crt", "server.key", "node-client-ca.crt", "node.kubeconfig", "node-config.yaml", "node-registration.json", "ca.crt")
	if !filenames.HasAll(expectedNames.List()...) || !expectedNames.HasAll(filenames.List()...) {
		t.Errorf("expected %v, got %v", expectedNames.List(), filenames.List())
	}
}
Exemplo n.º 2
0
func GetBootstrapServiceAccountProjectRoleBindings(namespace string) []authorizationapi.RoleBinding {
	return []authorizationapi.RoleBinding{
		{
			ObjectMeta: kapi.ObjectMeta{
				Name:      ImagePullerRoleBindingName,
				Namespace: namespace,
			},
			RoleRef: kapi.ObjectReference{
				Name: ImagePullerRoleName,
			},
			Groups: util.NewStringSet(serviceaccount.MakeNamespaceGroupName(namespace)),
		},
		{
			ObjectMeta: kapi.ObjectMeta{
				Name:      ImageBuilderRoleBindingName,
				Namespace: namespace,
			},
			RoleRef: kapi.ObjectReference{
				Name: ImageBuilderRoleName,
			},
			Users: util.NewStringSet(serviceaccount.MakeUsername(namespace, BuilderServiceAccountName)),
		},
		{
			ObjectMeta: kapi.ObjectMeta{
				Name:      DeployerRoleBindingName,
				Namespace: namespace,
			},
			RoleRef: kapi.ObjectReference{
				Name: DeployerRoleName,
			},
			Users: util.NewStringSet(serviceaccount.MakeUsername(namespace, DeployerServiceAccountName)),
		},
	}
}
Exemplo n.º 3
0
func (s *serviceAccount) limitSecretReferences(serviceAccount *api.ServiceAccount, pod *api.Pod) error {
	// Ensure all secrets the pod references are allowed by the service account
	mountableSecrets := util.NewStringSet()
	for _, s := range serviceAccount.Secrets {
		mountableSecrets.Insert(s.Name)
	}
	for _, volume := range pod.Spec.Volumes {
		source := volume.VolumeSource
		if source.Secret == nil {
			continue
		}
		secretName := source.Secret.SecretName
		if !mountableSecrets.Has(secretName) {
			return fmt.Errorf("Volume with secret.secretName=\"%s\" is not allowed because service account %s does not reference that secret", secretName, serviceAccount.Name)
		}
	}

	// limit pull secret references as well
	pullSecrets := util.NewStringSet()
	for _, s := range serviceAccount.ImagePullSecrets {
		pullSecrets.Insert(s.Name)
	}
	for i, pullSecretRef := range pod.Spec.ImagePullSecrets {
		if !pullSecrets.Has(pullSecretRef.Name) {
			return fmt.Errorf(`imagePullSecrets[%d].name="%s" is not allowed because service account %s does not reference that imagePullSecret`, i, pullSecretRef.Name, serviceAccount.Name)
		}
	}
	return nil
}
Exemplo n.º 4
0
func newInvalidExtensionPolicies() []authorizationapi.Policy {
	return []authorizationapi.Policy{
		{
			ObjectMeta: kapi.ObjectMeta{
				Name:      authorizationapi.PolicyName,
				Namespace: "mallet",
			},
			Roles: map[string]*authorizationapi.Role{
				"badExtension": {
					ObjectMeta: kapi.ObjectMeta{
						Name:      "failure",
						Namespace: "mallet",
					},
					Rules: []authorizationapi.PolicyRule{
						{
							Verbs:                 util.NewStringSet("watch", "list", "get"),
							Resources:             util.NewStringSet("buildConfigs"),
							AttributeRestrictions: runtime.EmbeddedObject{&authorizationapi.Role{}},
						},
						{
							Verbs:     util.NewStringSet("update"),
							Resources: util.NewStringSet("buildConfigs"),
						},
					},
				},
			},
		}}
}
Exemplo n.º 5
0
// syncRequest takes a reviewRequest and determines if it should update the caches supplied, it is not thread-safe
func (ac *AuthorizationCache) syncRequest(request *reviewRequest, userSubjectRecordStore cache.Store, groupSubjectRecordStore cache.Store, reviewRecordStore cache.Store) error {

	lastKnownValue, err := lastKnown(reviewRecordStore, request.namespace)
	if err != nil {
		return err
	}

	if skipReview(request, lastKnownValue) {
		return nil
	}

	namespace := request.namespace
	review, err := ac.reviewer.Review(namespace)
	if err != nil {
		return err
	}

	usersToRemove := util.NewStringSet()
	groupsToRemove := util.NewStringSet()
	if lastKnownValue != nil {
		usersToRemove.Insert(lastKnownValue.users...)
		usersToRemove.Delete(review.Users()...)
		groupsToRemove.Insert(lastKnownValue.groups...)
		groupsToRemove.Delete(review.Groups()...)
	}

	deleteNamespaceFromSubjects(userSubjectRecordStore, usersToRemove.List(), namespace)
	deleteNamespaceFromSubjects(groupSubjectRecordStore, groupsToRemove.List(), namespace)
	addSubjectsToNamespace(userSubjectRecordStore, review.Users(), namespace)
	addSubjectsToNamespace(groupSubjectRecordStore, review.Groups(), namespace)
	cacheReviewRecord(request, lastKnownValue, review, reviewRecordStore)
	return nil
}
Exemplo n.º 6
0
func TestWaitFlagNew(t *testing.T) {
	fcmd := exec.FakeCmd{
		CombinedOutputScript: []exec.FakeCombinedOutputAction{
			// iptables version check
			func() ([]byte, error) { return []byte("iptables v1.4.22"), nil },
			// Success.
			func() ([]byte, error) { return []byte{}, nil },
		},
	}
	fexec := exec.FakeExec{
		CommandScript: []exec.FakeCommandAction{
			func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) },
			func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) },
		},
	}
	runner := New(&fexec, ProtocolIpv4)
	err := runner.DeleteChain(TableNAT, Chain("FOOBAR"))
	if err != nil {
		t.Errorf("expected success, got %v", err)
	}
	if fcmd.CombinedOutputCalls != 2 {
		t.Errorf("expected 2 CombinedOutput() calls, got %d", fcmd.CombinedOutputCalls)
	}
	if !util.NewStringSet(fcmd.CombinedOutputLog[1]...).HasAll("iptables", "-w2") {
		t.Errorf("wrong CombinedOutput() log, got %s", fcmd.CombinedOutputLog[1])
	}
	if util.NewStringSet(fcmd.CombinedOutputLog[1]...).HasAny("-w") {
		t.Errorf("wrong CombinedOutput() log, got %s", fcmd.CombinedOutputLog[1])
	}
}
Exemplo n.º 7
0
func newDefaultClusterPolicyBindings() []authorizationapi.ClusterPolicyBinding {
	policyBinding := authorizationapi.ClusterPolicyBinding{
		ObjectMeta: kapi.ObjectMeta{
			Name: authorizationapi.ClusterPolicyBindingName,
		},
		RoleBindings: map[string]*authorizationapi.ClusterRoleBinding{
			"extra-cluster-admins": {
				ObjectMeta: kapi.ObjectMeta{
					Name: "cluster-admins",
				},
				RoleRef: kapi.ObjectReference{
					Name: "cluster-admin",
				},
				Users:  util.NewStringSet("ClusterAdmin"),
				Groups: util.NewStringSet("RootUsers"),
			},
			"user-only": {
				ObjectMeta: kapi.ObjectMeta{
					Name: "user-only",
				},
				RoleRef: kapi.ObjectReference{
					Name: "basic-user",
				},
				Users: util.NewStringSet("just-a-user"),
			},
		},
	}
	for key, value := range GetBootstrapPolicyBinding().RoleBindings {
		policyBinding.RoleBindings[key] = value
	}
	return []authorizationapi.ClusterPolicyBinding{policyBinding}
}
Exemplo n.º 8
0
func TestAdd(t *testing.T) {
	testCases := []struct {
		sel         Selector
		key         string
		operator    Operator
		values      []string
		refSelector Selector
	}{
		{
			LabelSelector{},
			"key",
			InOperator,
			[]string{"value"},
			LabelSelector{Requirement{"key", InOperator, util.NewStringSet("value")}},
		},
		{
			LabelSelector{Requirement{"key", InOperator, util.NewStringSet("value")}},
			"key2",
			EqualsOperator,
			[]string{"value2"},
			LabelSelector{
				Requirement{"key", InOperator, util.NewStringSet("value")},
				Requirement{"key2", EqualsOperator, util.NewStringSet("value2")},
			},
		},
	}
	for _, ts := range testCases {
		ts.sel = ts.sel.Add(ts.key, ts.operator, ts.values)
		if !reflect.DeepEqual(ts.sel, ts.refSelector) {
			t.Errorf("Expected %t found %t", ts.refSelector, ts.sel)
		}
	}
}
Exemplo n.º 9
0
// Test public interface
func doTestIndex(t *testing.T, indexer Indexer) {
	mkObj := func(id string, val string) testStoreObject {
		return testStoreObject{id: id, val: val}
	}

	// Test Index
	expected := map[string]util.StringSet{}
	expected["b"] = util.NewStringSet("a", "c")
	expected["f"] = util.NewStringSet("e")
	expected["h"] = util.NewStringSet("g")
	indexer.Add(mkObj("a", "b"))
	indexer.Add(mkObj("c", "b"))
	indexer.Add(mkObj("e", "f"))
	indexer.Add(mkObj("g", "h"))
	{
		for k, v := range expected {
			found := util.StringSet{}
			indexResults, err := indexer.Index("by_val", mkObj("", k))
			if err != nil {
				t.Errorf("Unexpected error %v", err)
			}
			for _, item := range indexResults {
				found.Insert(item.(testStoreObject).id)
			}
			items := v.List()
			if !found.HasAll(items...) {
				t.Errorf("missing items, index %s, expected %v but found %v", k, items, found.List())
			}
		}
	}
}
Exemplo n.º 10
0
// buildClientDiagnostics builds client Diagnostic objects based on the rawConfig passed in.
// Returns the Diagnostics built, "ok" bool for whether to proceed or abort, and an error if any was encountered during the building of diagnostics.) {
func (o DiagnosticsOptions) buildClientDiagnostics(rawConfig *clientcmdapi.Config) ([]types.Diagnostic, bool, error) {
	available := availableClientDiagnostics

	// osClient, kubeClient, clientErr := o.Factory.Clients() // use with a diagnostic that needs OpenShift/Kube client
	_, _, clientErr := o.Factory.Clients()
	if clientErr != nil {
		o.Logger.Notice("CED0001", "Failed creating client from config; client diagnostics will be limited to config testing")
		available = util.NewStringSet(clientdiags.ConfigContextsName)
	}

	diagnostics := []types.Diagnostic{}
	requestedDiagnostics := intersection(util.NewStringSet(o.RequestedDiagnostics...), available).List()
	for _, diagnosticName := range requestedDiagnostics {
		switch diagnosticName {
		case clientdiags.ConfigContextsName:
			for contextName := range rawConfig.Contexts {
				diagnostics = append(diagnostics, clientdiags.ConfigContext{rawConfig, contextName})
			}

		default:
			return nil, false, fmt.Errorf("unknown diagnostic: %v", diagnosticName)
		}
	}
	return diagnostics, true, clientErr
}
Exemplo n.º 11
0
func TestEscalating(t *testing.T) {
	escalatingResources := ExpandResources(util.NewStringSet(GroupsToResources[EscalatingResourcesGroupName]...))
	nonEscalatingResources := ExpandResources(util.NewStringSet(GroupsToResources[NonEscalatingResourcesGroupName]...))
	if len(nonEscalatingResources) <= len(escalatingResources) {
		t.Errorf("groups look bad: escalating=%v nonescalating=%v", escalatingResources.List(), nonEscalatingResources.List())
	}
}
Exemplo n.º 12
0
func TestNamespaceScopingFromEmpty(t *testing.T) {
	router := newTestRouter(make(map[string]ServiceUnit))
	templatePlugin := newDefaultTemplatePlugin(router)
	// TODO: move tests that rely on unique hosts to pkg/router/controller and remove them from
	// here
	plugin := controller.NewUniqueHost(templatePlugin, controller.HostForRoute)

	// no namespaces allowed
	plugin.HandleNamespaces(util.StringSet{})

	//add
	route := &routeapi.Route{
		ObjectMeta: kapi.ObjectMeta{Namespace: "foo", Name: "test"},
		Spec: routeapi.RouteSpec{
			Host: "www.example.com",
			To: kapi.ObjectReference{
				Name: "TestService",
			},
		},
	}

	// ignores all events for namespace that doesn't match
	for _, s := range []watch.EventType{watch.Added, watch.Modified, watch.Deleted} {
		plugin.HandleRoute(s, route)
		if _, ok := router.FindServiceUnit("foo/TestService"); ok || plugin.HostLen() != 0 {
			t.Errorf("unexpected router state %#v", router)
		}
	}

	// allow non matching
	plugin.HandleNamespaces(util.NewStringSet("bar"))
	for _, s := range []watch.EventType{watch.Added, watch.Modified, watch.Deleted} {
		plugin.HandleRoute(s, route)
		if _, ok := router.FindServiceUnit("foo/TestService"); ok || plugin.HostLen() != 0 {
			t.Errorf("unexpected router state %#v", router)
		}
	}

	// allow foo
	plugin.HandleNamespaces(util.NewStringSet("foo", "bar"))
	plugin.HandleRoute(watch.Added, route)
	if _, ok := router.FindServiceUnit("foo/TestService"); !ok || plugin.HostLen() != 1 {
		t.Errorf("unexpected router state %#v", router)
	}

	// forbid foo, and make sure it's cleared
	plugin.HandleNamespaces(util.NewStringSet("bar"))
	if _, ok := router.FindServiceUnit("foo/TestService"); ok || plugin.HostLen() != 0 {
		t.Errorf("unexpected router state %#v", router)
	}
	plugin.HandleRoute(watch.Modified, route)
	if _, ok := router.FindServiceUnit("foo/TestService"); ok || plugin.HostLen() != 0 {
		t.Errorf("unexpected router state %#v", router)
	}
	plugin.HandleRoute(watch.Added, route)
	if _, ok := router.FindServiceUnit("foo/TestService"); ok || plugin.HostLen() != 0 {
		t.Errorf("unexpected router state %#v", router)
	}
}
Exemplo n.º 13
0
func init() {
	// set the non-escalating groups
	GroupsToResources[OpenshiftNonEscalatingViewableGroupName] = ExpandResources(util.NewStringSet(GroupsToResources[OpenshiftAllGroupName]...)).
		Difference(ExpandResources(util.NewStringSet(GroupsToResources[OpenshiftEscalatingViewableGroupName]...))).List()

	GroupsToResources[KubeNonEscalatingViewableGroupName] = ExpandResources(util.NewStringSet(GroupsToResources[KubeAllGroupName]...)).
		Difference(ExpandResources(util.NewStringSet(GroupsToResources[KubeEscalatingViewableGroupName]...))).List()
}
Exemplo n.º 14
0
func convert_v1_ResourceAccessReviewResponse_To_api_ResourceAccessReviewResponse(in *ResourceAccessReviewResponse, out *newer.ResourceAccessReviewResponse, s conversion.Scope) error {
	if err := s.DefaultConvert(in, out, conversion.IgnoreMissingFields); err != nil {
		return err
	}

	out.Users = util.NewStringSet(in.UsersSlice...)
	out.Groups = util.NewStringSet(in.GroupsSlice...)

	return nil
}
Exemplo n.º 15
0
func convert_v1_ClusterRoleBinding_To_api_ClusterRoleBinding(in *ClusterRoleBinding, out *newer.ClusterRoleBinding, s conversion.Scope) error {
	if err := s.DefaultConvert(in, out, conversion.IgnoreMissingFields|conversion.AllowDifferentFieldTypeNames); err != nil {
		return err
	}

	out.Users = util.NewStringSet(in.UserNames...)
	out.Groups = util.NewStringSet(in.GroupNames...)

	return nil
}
Exemplo n.º 16
0
func TestToString(t *testing.T) {
	var req Requirement
	toStringTests := []struct {
		In    *LabelSelector
		Out   string
		Valid bool
	}{
		{&LabelSelector{
			getRequirement("x", InOperator, util.NewStringSet("abc", "def"), t),
			getRequirement("y", NotInOperator, util.NewStringSet("jkl"), t),
			getRequirement("z", ExistsOperator, nil, t)},
			"x in (abc,def),y notin (jkl),z", true},
		{&LabelSelector{
			getRequirement("x", InOperator, util.NewStringSet("abc", "def"), t),
			req}, // adding empty req for the trailing ','
			"x in (abc,def),", false},
		{&LabelSelector{
			getRequirement("x", NotInOperator, util.NewStringSet("abc"), t),
			getRequirement("y", InOperator, util.NewStringSet("jkl", "mno"), t),
			getRequirement("z", NotInOperator, util.NewStringSet(""), t)},
			"x notin (abc),y in (jkl,mno),z notin ()", true},
		{&LabelSelector{
			getRequirement("x", EqualsOperator, util.NewStringSet("abc"), t),
			getRequirement("y", DoubleEqualsOperator, util.NewStringSet("jkl"), t),
			getRequirement("z", NotEqualsOperator, util.NewStringSet("a"), t)},
			"x=abc,y==jkl,z!=a", true},
	}
	for _, ts := range toStringTests {
		if out := ts.In.String(); out == "" && ts.Valid {
			t.Errorf("%+v.String() => '%v' expected no error", ts.In, out)
		} else if out != ts.Out {
			t.Errorf("%+v.String() => '%v' want '%v'", ts.In, out, ts.Out)
		}
	}
}
func testSyncNamespaceThatIsTerminating(t *testing.T, experimentalMode bool) {
	mockClient := &testclient.Fake{}
	now := util.Now()
	testNamespace := api.Namespace{
		ObjectMeta: api.ObjectMeta{
			Name:              "test",
			ResourceVersion:   "1",
			DeletionTimestamp: &now,
		},
		Spec: api.NamespaceSpec{
			Finalizers: []api.FinalizerName{"kubernetes"},
		},
		Status: api.NamespaceStatus{
			Phase: api.NamespaceTerminating,
		},
	}
	err := syncNamespace(mockClient, experimentalMode, testNamespace)
	if err != nil {
		t.Errorf("Unexpected error when synching namespace %v", err)
	}
	// TODO: Reuse the constants for all these strings from testclient
	expectedActionSet := util.NewStringSet(
		strings.Join([]string{"list", "replicationcontrollers", ""}, "-"),
		strings.Join([]string{"list", "services", ""}, "-"),
		strings.Join([]string{"list", "pods", ""}, "-"),
		strings.Join([]string{"list", "resourcequotas", ""}, "-"),
		strings.Join([]string{"list", "secrets", ""}, "-"),
		strings.Join([]string{"list", "limitranges", ""}, "-"),
		strings.Join([]string{"list", "events", ""}, "-"),
		strings.Join([]string{"list", "serviceaccounts", ""}, "-"),
		strings.Join([]string{"list", "persistentvolumeclaims", ""}, "-"),
		strings.Join([]string{"create", "namespaces", "finalize"}, "-"),
		strings.Join([]string{"delete", "namespaces", ""}, "-"),
	)

	if experimentalMode {
		expectedActionSet.Insert(
			strings.Join([]string{"list", "horizontalpodautoscalers", ""}, "-"),
			strings.Join([]string{"list", "daemonsets", ""}, "-"),
			strings.Join([]string{"list", "deployments", ""}, "-"),
		)
	}

	actionSet := util.NewStringSet()
	for _, action := range mockClient.Actions() {
		actionSet.Insert(strings.Join([]string{action.GetVerb(), action.GetResource(), action.GetSubresource()}, "-"))
	}
	if !actionSet.HasAll(expectedActionSet.List()...) {
		t.Errorf("Expected actions: %v, but got: %v", expectedActionSet, actionSet)
	}
	if !expectedActionSet.HasAll(actionSet.List()...) {
		t.Errorf("Expected actions: %v, but got: %v", expectedActionSet, actionSet)
	}
}
Exemplo n.º 18
0
func (o *RemoveFromProjectOptions) Run() error {
	bindingList, err := o.Client.PolicyBindings(o.BindingNamespace).List(labels.Everything(), fields.Everything())
	if err != nil {
		return err
	}
	sort.Sort(authorizationapi.PolicyBindingSorter(bindingList.Items))

	usersRemoved := util.StringSet{}
	groupsRemoved := util.StringSet{}

	for _, currPolicyBinding := range bindingList.Items {
		for _, currBinding := range authorizationapi.SortRoleBindings(currPolicyBinding.RoleBindings, true) {
			bindingHasGroups := len(o.Groups) > 0 && currBinding.Groups.HasAny(o.Groups...)
			bindingHasUsers := len(o.Users) > 0 && currBinding.Users.HasAny(o.Users...)
			if !bindingHasGroups && !bindingHasUsers {
				continue
			}

			existingGroups := util.NewStringSet(currBinding.Groups.List()...)
			existingUsers := util.NewStringSet(currBinding.Users.List()...)

			currBinding.Groups.Delete(o.Groups...)
			currBinding.Users.Delete(o.Users...)

			_, err = o.Client.RoleBindings(o.BindingNamespace).Update(currBinding)
			if err != nil {
				return err
			}

			roleDisplayName := fmt.Sprintf("%s/%s", currBinding.RoleRef.Namespace, currBinding.RoleRef.Name)
			if len(currBinding.RoleRef.Namespace) == 0 {
				roleDisplayName = currBinding.RoleRef.Name
			}
			if diff := existingGroups.Difference(currBinding.Groups); len(diff) != 0 {
				fmt.Fprintf(o.Out, "Removing %s from groups %v in project %s.\n", roleDisplayName, diff.List(), o.BindingNamespace)
				groupsRemoved.Insert(diff.List()...)
			}
			if diff := existingUsers.Difference(currBinding.Users); len(diff) != 0 {
				fmt.Fprintf(o.Out, "Removing %s from users %v in project %s.\n", roleDisplayName, diff.List(), o.BindingNamespace)
				usersRemoved.Insert(diff.List()...)
			}
		}
	}

	if diff := util.NewStringSet(o.Groups...).Difference(groupsRemoved); len(diff) != 0 {
		fmt.Fprintf(o.Out, "Groups %v were not bound to roles in project %s.\n", diff.List(), o.BindingNamespace)
	}
	if diff := util.NewStringSet(o.Users...).Difference(usersRemoved); len(diff) != 0 {
		fmt.Fprintf(o.Out, "Users %v were not bound to roles in project %s.\n", diff.List(), o.BindingNamespace)
	}

	return nil
}
func TestPrinters(t *testing.T) {
	om := func(name string) api.ObjectMeta { return api.ObjectMeta{Name: name} }
	templatePrinter, err := NewTemplatePrinter([]byte("{{.name}}"))
	if err != nil {
		t.Fatal(err)
	}
	templatePrinter2, err := NewTemplatePrinter([]byte("{{len .items}}"))
	if err != nil {
		t.Fatal(err)
	}
	jsonpathPrinter, err := NewJSONPathPrinter("{.metadata.name}")
	if err != nil {
		t.Fatal(err)
	}
	printers := map[string]ResourcePrinter{
		"humanReadable":        NewHumanReadablePrinter(true, false, false, false, []string{}),
		"humanReadableHeaders": NewHumanReadablePrinter(false, false, false, false, []string{}),
		"json":                 &JSONPrinter{},
		"yaml":                 &YAMLPrinter{},
		"template":             templatePrinter,
		"template2":            templatePrinter2,
		"jsonpath":             jsonpathPrinter,
		"name":                 &NamePrinter{},
	}
	objects := map[string]runtime.Object{
		"pod":             &api.Pod{ObjectMeta: om("pod")},
		"emptyPodList":    &api.PodList{},
		"nonEmptyPodList": &api.PodList{Items: []api.Pod{{}}},
		"endpoints": &api.Endpoints{
			Subsets: []api.EndpointSubset{{
				Addresses: []api.EndpointAddress{{IP: "127.0.0.1"}, {IP: "localhost"}},
				Ports:     []api.EndpointPort{{Port: 8080}},
			}}},
	}
	// map of printer name to set of objects it should fail on.
	expectedErrors := map[string]util.StringSet{
		"template2": util.NewStringSet("pod", "emptyPodList", "endpoints"),
		"jsonpath":  util.NewStringSet("emptyPodList", "nonEmptyPodList", "endpoints"),
	}

	for pName, p := range printers {
		for oName, obj := range objects {
			b := &bytes.Buffer{}
			if err := p.PrintObj(obj, b); err != nil {
				if set, found := expectedErrors[pName]; found && set.Has(oName) {
					// expected error
					continue
				}
				t.Errorf("printer '%v', object '%v'; error: '%v'", pName, oName, err)
			}
		}
	}
}
Exemplo n.º 20
0
func TestNamespaceScopingFromEmpty(t *testing.T) {
	router := newTestRouter(make(map[string]ServiceUnit))
	plugin := newDefaultTemplatePlugin(router)

	// no namespaces allowed
	plugin.HandleNamespaces(util.StringSet{})

	//add
	route := &routeapi.Route{
		ObjectMeta:  kapi.ObjectMeta{Namespace: "foo", Name: "test"},
		Host:        "www.example.com",
		ServiceName: "TestService",
	}

	// ignores all events for namespace that doesn't match
	for _, s := range []watch.EventType{watch.Added, watch.Modified, watch.Deleted} {
		plugin.HandleRoute(s, route)
		if _, ok := router.FindServiceUnit("foo/TestService"); ok || len(plugin.hostToRoute) != 0 {
			t.Errorf("unexpected router state %#v", router)
		}
	}

	// allow non matching
	plugin.HandleNamespaces(util.NewStringSet("bar"))
	for _, s := range []watch.EventType{watch.Added, watch.Modified, watch.Deleted} {
		plugin.HandleRoute(s, route)
		if _, ok := router.FindServiceUnit("foo/TestService"); ok || len(plugin.hostToRoute) != 0 {
			t.Errorf("unexpected router state %#v", router)
		}
	}

	// allow foo
	plugin.HandleNamespaces(util.NewStringSet("foo", "bar"))
	plugin.HandleRoute(watch.Added, route)
	if _, ok := router.FindServiceUnit("foo/TestService"); !ok || len(plugin.hostToRoute) != 1 {
		t.Errorf("unexpected router state %#v", router)
	}

	// forbid foo, and make sure it's cleared
	plugin.HandleNamespaces(util.NewStringSet("bar"))
	if _, ok := router.FindServiceUnit("foo/TestService"); ok || len(plugin.hostToRoute) != 0 {
		t.Errorf("unexpected router state %#v", router)
	}
	plugin.HandleRoute(watch.Modified, route)
	if _, ok := router.FindServiceUnit("foo/TestService"); ok || len(plugin.hostToRoute) != 0 {
		t.Errorf("unexpected router state %#v", router)
	}
	plugin.HandleRoute(watch.Added, route)
	if _, ok := router.FindServiceUnit("foo/TestService"); ok || len(plugin.hostToRoute) != 0 {
		t.Errorf("unexpected router state %#v", router)
	}
}
Exemplo n.º 21
0
// Makes sure that exactly the specified hosts are registered as instances with the load balancer
func (s *AWSCloud) ensureLoadBalancerInstances(elbClient ELB, loadBalancerName string, lbInstances []*elb.Instance, instances []*ec2.Instance) error {
	expected := util.NewStringSet()
	for _, instance := range instances {
		expected.Insert(orEmpty(instance.InstanceID))
	}

	actual := util.NewStringSet()
	for _, lbInstance := range lbInstances {
		actual.Insert(orEmpty(lbInstance.InstanceID))
	}

	additions := expected.Difference(actual)
	removals := actual.Difference(expected)

	addInstances := []*elb.Instance{}
	for instanceId := range additions {
		addInstance := &elb.Instance{}
		addInstance.InstanceID = aws.String(instanceId)
		addInstances = append(addInstances, addInstance)
	}

	removeInstances := []*elb.Instance{}
	for instanceId := range removals {
		removeInstance := &elb.Instance{}
		removeInstance.InstanceID = aws.String(instanceId)
		removeInstances = append(removeInstances, removeInstance)
	}

	if len(addInstances) > 0 {
		registerRequest := &elb.RegisterInstancesWithLoadBalancerInput{}
		registerRequest.Instances = addInstances
		registerRequest.LoadBalancerName = aws.String(loadBalancerName)
		_, err := elbClient.RegisterInstancesWithLoadBalancer(registerRequest)
		if err != nil {
			return err
		}
		glog.V(1).Infof("Instances added to load-balancer %s", loadBalancerName)
	}

	if len(removeInstances) > 0 {
		deregisterRequest := &elb.DeregisterInstancesFromLoadBalancerInput{}
		deregisterRequest.Instances = removeInstances
		deregisterRequest.LoadBalancerName = aws.String(loadBalancerName)
		_, err := elbClient.DeregisterInstancesFromLoadBalancer(deregisterRequest)
		if err != nil {
			return err
		}
		glog.V(1).Infof("Instances removed from load-balancer %s", loadBalancerName)
	}

	return nil
}
Exemplo n.º 22
0
func TestEnumeratedCoveringResourceGroup(t *testing.T) {
	escalationTest{
		ownerRules: []authorizationapi.PolicyRule{
			{Verbs: util.NewStringSet("delete", "update"), Resources: util.NewStringSet("builds", "buildconfigs", "buildlogs", "buildconfigs/instantiate", "builds/log", "builds/clone", "buildconfigs/webhooks")},
		},
		servantRules: []authorizationapi.PolicyRule{
			{Verbs: util.NewStringSet("delete", "update"), Resources: util.NewStringSet("resourcegroup:builds")},
		},

		expectedCovered:        true,
		expectedUncoveredRules: []authorizationapi.PolicyRule{},
	}.test(t)
}
Exemplo n.º 23
0
func TestVerbStarCoveringMultiple(t *testing.T) {
	escalationTest{
		ownerRules: []authorizationapi.PolicyRule{
			{Verbs: util.NewStringSet("*"), Resources: util.NewStringSet("roles")},
		},
		servantRules: []authorizationapi.PolicyRule{
			{Verbs: util.NewStringSet("watch", "list"), Resources: util.NewStringSet("roles")},
		},

		expectedCovered:        true,
		expectedUncoveredRules: []authorizationapi.PolicyRule{},
	}.test(t)
}
Exemplo n.º 24
0
func TestResourceStarCoveringStar(t *testing.T) {
	escalationTest{
		ownerRules: []authorizationapi.PolicyRule{
			{Verbs: util.NewStringSet("get"), Resources: util.NewStringSet("*")},
		},
		servantRules: []authorizationapi.PolicyRule{
			{Verbs: util.NewStringSet("get"), Resources: util.NewStringSet("*")},
		},

		expectedCovered:        true,
		expectedUncoveredRules: []authorizationapi.PolicyRule{},
	}.test(t)
}
Exemplo n.º 25
0
func TestResourceNameEmptyCoveringMultiple(t *testing.T) {
	escalationTest{
		ownerRules: []authorizationapi.PolicyRule{
			{Verbs: util.NewStringSet("get"), Resources: util.NewStringSet("pods"), ResourceNames: util.NewStringSet()},
		},
		servantRules: []authorizationapi.PolicyRule{
			{Verbs: util.NewStringSet("get"), Resources: util.NewStringSet("pods"), ResourceNames: util.NewStringSet("foo", "bar")},
		},

		expectedCovered:        true,
		expectedUncoveredRules: []authorizationapi.PolicyRule{},
	}.test(t)
}
Exemplo n.º 26
0
func TestResourceGroupCoveringEnumerated(t *testing.T) {
	escalationTest{
		ownerRules: []authorizationapi.PolicyRule{
			{Verbs: util.NewStringSet("create", "delete", "update"), Resources: util.NewStringSet("resourcegroup:builds")},
		},
		servantRules: []authorizationapi.PolicyRule{
			{Verbs: util.NewStringSet("delete", "update"), Resources: util.NewStringSet("builds", "buildconfigs")},
		},

		expectedCovered:        true,
		expectedUncoveredRules: []authorizationapi.PolicyRule{},
	}.test(t)
}
Exemplo n.º 27
0
func TestSyncNamespaceThatIsTerminating(t *testing.T) {
	mockKubeClient := &ktestclient.Fake{}
	mockOriginClient := &testclient.Fake{}
	nm := NamespaceController{
		KubeClient: mockKubeClient,
		Client:     mockOriginClient,
	}
	now := util.Now()
	testNamespace := &kapi.Namespace{
		ObjectMeta: kapi.ObjectMeta{
			Name:              "test",
			ResourceVersion:   "1",
			DeletionTimestamp: &now,
		},
		Spec: kapi.NamespaceSpec{
			Finalizers: []kapi.FinalizerName{kapi.FinalizerKubernetes, api.FinalizerOrigin},
		},
		Status: kapi.NamespaceStatus{
			Phase: kapi.NamespaceTerminating,
		},
	}
	err := nm.Handle(testNamespace)
	if err != nil {
		t.Errorf("Unexpected error when handling namespace %v", err)
	}

	// TODO: we will expect a finalize namespace call after rebase
	expectedActionSet := util.NewStringSet(
		"list-buildconfig",
		"list-policies",
		"list-imagestreams",
		"list-policyBindings",
		"list-roleBinding",
		"list-role",
		"list-routes",
		"list-templates",
		"list-builds",
		"finalize-namespace",
		"list-deploymentconfig",
	)
	actionSet := util.NewStringSet()
	for i := range mockKubeClient.Actions() {
		actionSet.Insert(mockKubeClient.Actions()[i].Action)
	}
	for i := range mockOriginClient.Actions {
		actionSet.Insert(mockOriginClient.Actions[i].Action)
	}
	if !(actionSet.HasAll(expectedActionSet.List()...) && (len(actionSet) == len(expectedActionSet))) {
		t.Errorf("Expected actions: %v, but got: %v", expectedActionSet, actionSet)
	}
}
Exemplo n.º 28
0
func (im *realImageManager) detectImages(detected time.Time) error {
	images, err := im.dockerClient.ListImages(docker.ListImagesOptions{})
	if err != nil {
		return err
	}
	containers, err := im.dockerClient.ListContainers(docker.ListContainersOptions{
		All: true,
	})
	if err != nil {
		return err
	}

	// Make a set of images in use by containers.
	imagesInUse := util.NewStringSet()
	for _, container := range containers {
		imagesInUse.Insert(container.Image)
	}

	// Add new images and record those being used.
	now := time.Now()
	currentImages := util.NewStringSet()
	im.imageRecordsLock.Lock()
	defer im.imageRecordsLock.Unlock()
	for _, image := range images {
		currentImages.Insert(image.ID)

		// New image, set it as detected now.
		if _, ok := im.imageRecords[image.ID]; !ok {
			im.imageRecords[image.ID] = &imageRecord{
				detected: detected,
			}
		}

		// Set last used time to now if the image is being used.
		if isImageUsed(&image, imagesInUse) {
			im.imageRecords[image.ID].lastUsed = now
		}

		im.imageRecords[image.ID].size = image.VirtualSize
	}

	// Remove old images from our records.
	for image := range im.imageRecords {
		if !currentImages.Has(image) {
			delete(im.imageRecords, image)
		}
	}

	return nil
}
Exemplo n.º 29
0
func TestNoErrors(t *testing.T) {
	test := &resourceAccessTest{
		authorizer: &testAuthorizer{
			users:  util.NewStringSet("one", "two"),
			groups: util.NewStringSet("three", "four"),
		},
		reviewRequest: &authorizationapi.ResourceAccessReview{
			Verb:     "delete",
			Resource: "deploymentConfig",
		},
	}

	test.runTest(t)
}
Exemplo n.º 30
0
func TestEnumerationNotCoveringVerbStar(t *testing.T) {
	escalationTest{
		ownerRules: []authorizationapi.PolicyRule{
			{Verbs: util.NewStringSet("get", "list", "watch", "create", "update", "delete", "exec"), Resources: util.NewStringSet("roles")},
		},
		servantRules: []authorizationapi.PolicyRule{
			{Verbs: util.NewStringSet("*"), Resources: util.NewStringSet("roles")},
		},

		expectedCovered: false,
		expectedUncoveredRules: []authorizationapi.PolicyRule{
			{Verbs: util.NewStringSet("*"), Resources: util.NewStringSet("roles")},
		},
	}.test(t)
}