Skip to content

Instantly share code, notes, and snippets.

@Yapcheekian
Created March 4, 2022 00:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Yapcheekian/d5507aacc5b1222b758be34c466c4e54 to your computer and use it in GitHub Desktop.
Save Yapcheekian/d5507aacc5b1222b758be34c466c4e54 to your computer and use it in GitHub Desktop.
k8s authorization webhook
package authorize
import (
"encoding/json"
"fmt"
"log"
"net/http"
authorization "k8s.io/api/authorization/v1beta1"
)
const NAMESPACE = "protected"
func Authorize(w http.ResponseWriter, r *http.Request) {
decoder := json.NewDecoder(r.Body)
var sar authorization.SubjectAccessReview
err := decoder.Decode(&sar)
if err != nil {
log.Println("[Error]", err.Error())
sar := new(authorization.SubjectAccessReview)
status := authorization.SubjectAccessReviewStatus{
Allowed: false,
Reason: err.Error(),
}
sar.Status = status
w.WriteHeader(http.StatusUnauthorized)
json.NewEncoder(w).Encode(sar)
return
}
if sar.Spec.ResourceAttributes != nil {
v := sar.Spec.ResourceAttributes.Verb
n := sar.Spec.ResourceAttributes.Namespace
if n == NAMESPACE && (v == "create" || v == "delete" || v == "update") {
log.Printf("[Not Allowed] %s in namespace %s", sar.Spec.ResourceAttributes.Verb, NAMESPACE)
response := new(authorization.SubjectAccessReview)
status := authorization.SubjectAccessReviewStatus{
Allowed: false,
Denied: true,
Reason: fmt.Sprintf("%s is not allowed in the namespace: %s", sar.Spec.ResourceAttributes.Verb, NAMESPACE),
}
response.Status = status
json.NewEncoder(w).Encode(response)
return
}
}
response := new(authorization.SubjectAccessReview)
status := authorization.SubjectAccessReviewStatus{
Allowed: true,
}
response.Status = status
json.NewEncoder(w).Encode(response)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment