Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Access token removal fix on hook removal #109

Merged
merged 2 commits into from
Jul 29, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions cmd/ginvalid/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,13 +62,13 @@ func startupCheck(srvcfg config.ServerCfg) {
os.Exit(-1)
}

log.ShowWrite("[Warmup] using temp directory: '%s'", srvcfg.Dir.Temp)
log.ShowWrite("[Warmup] using results directory '%s'", srvcfg.Dir.Result)
log.ShowWrite("[Warmup] using temp directory: %q", srvcfg.Dir.Temp)
log.ShowWrite("[Warmup] using results directory %q", srvcfg.Dir.Result)

// Check bids-validator is installed
outstr, err := helpers.AppVersionCheck(srvcfg.Exec.BIDS)
if err != nil {
log.ShowWrite("[Error] checking bids-validator '%s'", err.Error())
log.ShowWrite("[Error] checking bids-validator %q", err.Error())
os.Exit(-1)
}
log.ShowWrite("[Warmup] using bids-validator v%s", strings.TrimSpace(outstr))
Expand Down Expand Up @@ -110,7 +110,7 @@ func commcheck(srvcfg config.ServerCfg) {
cli := ginclient.New("gin")
err = cli.Login(srvcfg.Settings.GINUser, srvcfg.Settings.GINPassword, srvcfg.Settings.ClientID)
if err != nil {
log.ShowWrite("Failed to login to GIN server: %s", err.Error())
log.ShowWrite("[Error] Failed to login to GIN server: %s", err.Error())
os.Exit(-1)
}
log.ShowWrite("[Warmup] GIN server configuration OK")
Expand Down Expand Up @@ -171,7 +171,7 @@ func main() {
port = srvcfg.Settings.Port
}
port = fmt.Sprintf(":%s", port)
log.ShowWrite("[Warmup] using port: '%s'", port)
log.ShowWrite("[Warmup] using port: %q", port)

log.ShowWrite("[Warmup] registering routes")
router := mux.NewRouter()
Expand Down
4 changes: 2 additions & 2 deletions internal/helpers/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ func ValidDirectory(path string) bool {
var fi os.FileInfo
var err error
if fi, err = os.Stat(path); err != nil {
log.ShowWrite("[Error] checking directory '%s': '%s'\n", path, err.Error())
log.ShowWrite("[Error] checking directory %q: %q", path, err.Error())
return false
} else if !fi.IsDir() {
log.ShowWrite("[Error] invalid directory '%s'\n", fi.Name())
log.ShowWrite("[Error] invalid directory %q", fi.Name())
return false
}
return true
Expand Down
10 changes: 5 additions & 5 deletions internal/web/fail.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,21 +13,21 @@ import (
// fail logs an error and renders an error page with the given message,
// returning the given status code to the user.
func fail(w http.ResponseWriter, r *http.Request, status int, message string) {
log.Write("[error] %s", message)
log.ShowWrite("[Info] displaying error message %s", message)
w.WriteHeader(status)

tmpl := template.New("layout")
tmpl, err := tmpl.Parse(templates.Layout)
if err != nil {
log.Write("[Error] failed to parse html layout page. Displaying error message without layout.")
log.ShowWrite("[Error] failed to parse html layout page. Displaying error message without layout: %s", err.Error())
tmpl = template.New("content")
}
tmpl, err = tmpl.Parse(templates.Fail)
if err != nil {
log.Write("[Error] failed to render fail page. Displaying plain error message.")
log.ShowWrite("[Error] failed to render fail page. Displaying plain error message: %s", err.Error())
_, err = w.Write([]byte(message))
if err != nil {
log.Write("[Error] failed to write plain error message: %s", err.Error())
log.ShowWrite("[Error] failed to write plain error message: %s", err.Error())
}
return
}
Expand All @@ -54,6 +54,6 @@ func fail(w http.ResponseWriter, r *http.Request, status int, message string) {
}
err = tmpl.Execute(w, &errinfo)
if err != nil {
log.Write("[Error] failed to parse error info to page: %s", err.Error())
log.ShowWrite("[Error] failed to parse error info to page: %s", err.Error())
}
}
7 changes: 3 additions & 4 deletions internal/web/ginutils.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ func isGitRepo(path string) bool {
// This function is a modified version of the gin-client CloneRepo method.
func remoteCloneRepo(gincl *ginclient.Client, repopath, clonedir string, clonechan chan<- gingit.RepoFileStatus) {
defer close(clonechan)
log.ShowWrite("[Info] Starting remoteCloneRepo")
log.ShowWrite("[Info] starting remoteCloneRepo")
clonestatus := make(chan gingit.RepoFileStatus)
remotepath := fmt.Sprintf("%s/%s", gincl.GitAddress(), repopath)

Expand Down Expand Up @@ -438,8 +438,7 @@ func remoteAnnexGet(gitdir string, getchan chan<- gingit.RepoFileStatus, rawMode
err = json.Unmarshal(outline, &getresult)
if err != nil || getresult.Command == "" {
// Couldn't parse output
log.ShowWrite("[Warning] Could not parse 'git annex get' output")
log.ShowWrite(string(outline))
log.ShowWrite("[Warning] Could not parse 'git annex get' output: %s", string(outline))
// TODO: Print error at the end: Command succeeded but there was an error understanding the output
continue
}
Expand Down Expand Up @@ -490,7 +489,7 @@ func remoteCommitCheckout(gitdir, hash string) error {
cmd.Args = cmdargs
_, stderr, err := cmd.OutputError()
if err != nil {
log.ShowWrite("[Error] %s; %s", err.Error(), string(stderr))
log.ShowWrite("[Error] err: %s; stderr: %s", err.Error(), string(stderr))
return fmt.Errorf(string(stderr))
}
return nil
Expand Down
39 changes: 26 additions & 13 deletions internal/web/hooks.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ func EnableHook(w http.ResponseWriter, r *http.Request) {
validator := strings.ToLower(vars["validator"])
ut, err := getSessionOrRedirect(w, r)
if err != nil {
log.Write("[Info] %s: Redirecting to login", err.Error())
log.ShowWrite("[Info] %s: redirecting to login", err.Error())
return
}
if !helpers.SupportedValidator(validator) {
Expand Down Expand Up @@ -61,15 +61,16 @@ func DisableHook(w http.ResponseWriter, r *http.Request) {

ut, err := getSessionOrRedirect(w, r)
if err != nil {
log.Write("[Info] %s: Redirecting to login", err.Error())
log.ShowWrite("[Info] %s: redirecting to login", err.Error())
return
}

repopath := fmt.Sprintf("%s/%s", user, repo)
err = deleteValidHook(repopath, hookid, ut)
if err != nil {
// TODO: Check if failure is for other reasons and maybe return 500 instead
fail(w, r, http.StatusUnauthorized, err.Error())
log.ShowWrite(err.Error())
fail(w, r, http.StatusUnauthorized, "Could not remove hook")
return
}
http.Redirect(w, r, fmt.Sprintf("/repos/%s/hooks", repopath), http.StatusFound)
Expand All @@ -88,7 +89,7 @@ func createValidHook(repopath string, validator string, usertoken gweb.UserToken
// TODO: AVOID DUPLICATES:
// - If it's already hooked and we have it on record, do nothing
// - If it's already hooked, but we don't know about it, check if it's valid and don't recreate
log.Write("Adding %s hook to %s\n", validator, repopath)
log.ShowWrite("[Info] adding %q hook to %q", validator, repopath)

cfg := config.Read()
client := ginclient.New(serveralias)
Expand All @@ -98,7 +99,7 @@ func createValidHook(repopath string, validator string, usertoken gweb.UserToken

u, err := url.Parse(cfg.Settings.RootURL)
if err != nil {
log.Write("[error] failed to parse url: %s", err.Error())
log.ShowWrite("[Error] failed to parse url: %s", err.Error())
return fmt.Errorf("hook creation failed: %s", err.Error())
}
u.Path = path.Join(u.Path, "validate", validator, repopath)
Expand All @@ -113,13 +114,13 @@ func createValidHook(repopath string, validator string, usertoken gweb.UserToken
}
res, err := client.Post(fmt.Sprintf("/api/v1/repos/%s/hooks", repopath), data)
if err != nil {
log.Write("[error] failed to post: %s", err.Error())
log.ShowWrite("[Error] failed to post: %s", err.Error())
return fmt.Errorf("hook creation failed: %s", err.Error())
}
defer res.Body.Close()

if res.StatusCode != http.StatusCreated {
log.Write("[error] non-OK response: %s", res.Status)
log.ShowWrite("[Error] non-OK response: %s", res.Status)
return fmt.Errorf("hook creation failed: %s", res.Status)
}

Expand All @@ -128,23 +129,35 @@ func createValidHook(repopath string, validator string, usertoken gweb.UserToken
}

func deleteValidHook(repopath string, id int, usertoken gweb.UserToken) error {
log.Write("Deleting %d from %s\n", id, repopath)
log.ShowWrite("[Info] deleting hook %d from %q", id, repopath)

client := ginclient.New(serveralias)
client.UserToken = usertoken

res, err := client.Delete(fmt.Sprintf("/api/v1/repos/%s/hooks/%d", repopath, id))
if err != nil {
log.Write("[error] bad response from server %s", err.Error())
return err
return fmt.Errorf("[Error] bad response from server: %s", err.Error())
}
defer res.Body.Close()
log.Write("[info] removed hook for %s", repopath)
log.ShowWrite("[Info] removed hook for %s", repopath)

// delete repo token only if there are no more hooks registered for the current repo
hooks, err := getRepoHooks(client, repopath)
if err != nil {
return fmt.Errorf("[Error] checking remaining repo hooks: %s", err.Error())
}
// return without removing the repo->token link if a single active hook is found
log.ShowWrite("[Info] current repo hooks: %v", hooks)
for valname := range hooks {
if hooks[valname].State == hookenabled {
return nil
}
}

log.Write("[info] removing repository -> token link")
log.ShowWrite("[Info] found no active hook, removing repository -> token link")
err = rmTokenRepoLink(repopath)
if err != nil {
log.Write("[error] failed to delete token link: %s", err.Error())
log.ShowWrite("[Error] failed to delete token link: %s", err.Error())
// don't fail
}

Expand Down
42 changes: 21 additions & 21 deletions internal/web/results.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,11 +120,11 @@ func Results(w http.ResponseWriter, r *http.Request) {
repo := vars["repo"]
validator := strings.ToLower(vars["validator"])
if !helpers.SupportedValidator(validator) {
log.ShowWrite("[Error] unsupported validator '%s'\n", validator)
log.ShowWrite("[Error] unsupported validator '%s'", validator)
http.ServeContent(w, r, "unavailable", time.Now(), bytes.NewReader([]byte("404 Nothing to see here...")))
return
}
log.ShowWrite("[Info] '%s' results for repo '%s/%s'\n", validator, user, repo)
log.ShowWrite("[Info] %q results for repo '%s/%s'", validator, user, repo)

srvcfg := config.Read()
resID, ok := vars["id"]
Expand All @@ -143,7 +143,7 @@ func Results(w http.ResponseWriter, r *http.Request) {
fp := filepath.Join(resdir, srvcfg.Label.ResultsBadge)
badge, err := ioutil.ReadFile(fp)
if err != nil {
log.ShowWrite("[Error] serving '%s/%s' badge: %s\n", user, repo, err.Error())
log.ShowWrite("[Error] serving '%s/%s' badge: %s", user, repo, err.Error())
}

fp = filepath.Join(resdir, srvcfg.Label.ResultsFile)
Expand Down Expand Up @@ -176,13 +176,13 @@ func notValidatedYet(w http.ResponseWriter, r *http.Request, badge []byte, valid
tmpl := template.New("layout")
tmpl, err := tmpl.Parse(templates.Layout)
if err != nil {
log.ShowWrite("[Error] '%s/%s' result: %s\n", user, repo, err.Error())
log.ShowWrite("[Error] '%s/%s' result: %s", user, repo, err.Error())
http.ServeContent(w, r, "unavailable", time.Now(), bytes.NewReader([]byte("500 Something went wrong...")))
return
}
tmpl, err = tmpl.Parse(templates.NotValidatedYet)
if err != nil {
log.ShowWrite("[Error] '%s/%s' result: %s\n", user, repo, err.Error())
log.ShowWrite("[Error] '%s/%s' result: %s", user, repo, err.Error())
http.ServeContent(w, r, "unavailable", time.Now(), bytes.NewReader([]byte("500 Something went wrong...")))
return
}
Expand Down Expand Up @@ -213,7 +213,7 @@ func notValidatedYet(w http.ResponseWriter, r *http.Request, badge []byte, valid

err = tmpl.ExecuteTemplate(w, "layout", info)
if err != nil {
log.ShowWrite("[Error] '%s/%s' result: %s\n", user, repo, err.Error())
log.ShowWrite("[Error] '%s/%s' result: %s", user, repo, err.Error())
http.ServeContent(w, r, "unavailable", time.Now(), bytes.NewReader([]byte("500 Something went wrong...")))
return
}
Expand All @@ -223,13 +223,13 @@ func renderInProgress(w http.ResponseWriter, r *http.Request, badge []byte, vali
tmpl := template.New("layout")
tmpl, err := tmpl.Parse(templates.Layout)
if err != nil {
log.ShowWrite("[Error] '%s/%s' result: %s\n", user, repo, err.Error())
log.ShowWrite("[Error] '%s/%s' result: %s", user, repo, err.Error())
http.ServeContent(w, r, "unavailable", time.Now(), bytes.NewReader([]byte("500 Something went wrong...")))
return
}
tmpl, err = tmpl.Parse(templates.GenericResults)
if err != nil {
log.ShowWrite("[Error] '%s/%s' result: %s\n", user, repo, err.Error())
log.ShowWrite("[Error] '%s/%s' result: %s", user, repo, err.Error())
http.ServeContent(w, r, "unavailable", time.Now(), bytes.NewReader([]byte("500 Something went wrong...")))
return
}
Expand All @@ -252,7 +252,7 @@ func renderInProgress(w http.ResponseWriter, r *http.Request, badge []byte, vali

err = tmpl.ExecuteTemplate(w, "layout", info)
if err != nil {
log.ShowWrite("[Error] '%s/%s' result: %s\n", user, repo, err.Error())
log.ShowWrite("[Error] '%s/%s' result: %s", user, repo, err.Error())
http.ServeContent(w, r, "unavailable", time.Now(), bytes.NewReader([]byte("500 Something went wrong...")))
return
}
Expand All @@ -278,7 +278,7 @@ func resultsHistory(validator, user, repo string) ResultsHistoryStruct {
resdir := filepath.Join(srvcfg.Dir.Result, validator, user, repo)
fileinfos, err := myReadDir(resdir)
if err != nil {
log.ShowWrite("[Error] cannot retrieve results history '%s/%s' result: %s\n", user, repo, err.Error())
log.ShowWrite("[Error] cannot retrieve results history '%s/%s' result: %s", user, repo, err.Error())
return ret
}
for _, i := range fileinfos {
Expand All @@ -292,7 +292,7 @@ func resultsHistory(validator, user, repo string) ResultsHistoryStruct {
var res Result
res.Href = pth
res.Alt = i.Name()
res.Text1 = i.ModTime().Format("2006-01-02")
res.Text1 = i.ModTime().UTC().Format("2006-01-02")
res.Text2 = i.ModTime().Format("15:04:05")
res.Badge = template.HTML(badge)
ret.Results = append(ret.Results, res)
Expand All @@ -307,21 +307,21 @@ func renderBIDSResults(w http.ResponseWriter, r *http.Request, badge []byte, con
err := json.Unmarshal(content, &resBIDS)
errMsg := ""
if err != nil {
log.ShowWrite("[Error] unmarshalling '%s/%s' result: %s\n", user, repo, err.Error())
log.ShowWrite("[Error] unmarshalling '%s/%s' result: %s", user, repo, err.Error())
errMsg = "Could not validate format as BIDS."
}

// Parse html template
tmpl := template.New("layout")
tmpl, err = tmpl.Parse(templates.Layout)
if err != nil {
log.ShowWrite("[Error] '%s/%s' result: %s\n", user, repo, err.Error())
log.ShowWrite("[Error] '%s/%s' result: %s", user, repo, err.Error())
http.ServeContent(w, r, "unavailable", time.Now(), bytes.NewReader([]byte("500 Something went wrong...")))
return
}
tmpl, err = tmpl.Parse(templates.BidsResults)
if err != nil {
log.ShowWrite("[Error] '%s/%s' result: %s\n", user, repo, err.Error())
log.ShowWrite("[Error] '%s/%s' result: %s", user, repo, err.Error())
http.ServeContent(w, r, "unavailable", time.Now(), bytes.NewReader([]byte("500 Something went wrong...")))
return
}
Expand All @@ -345,7 +345,7 @@ func renderBIDSResults(w http.ResponseWriter, r *http.Request, badge []byte, con

err = tmpl.ExecuteTemplate(w, "layout", info)
if err != nil {
log.ShowWrite("[Error] '%s/%s' result: %s\n", user, repo, err.Error())
log.ShowWrite("[Error] '%s/%s' result: %s", user, repo, err.Error())
http.ServeContent(w, r, "unavailable", time.Now(), bytes.NewReader([]byte("500 Something went wrong...")))
return
}
Expand All @@ -357,13 +357,13 @@ func renderNIXResults(w http.ResponseWriter, r *http.Request, badge []byte, cont
tmpl := template.New("layout")
tmpl, err := tmpl.Parse(templates.Layout)
if err != nil {
log.ShowWrite("[Error] '%s/%s' result: %s\n", user, repo, err.Error())
log.ShowWrite("[Error] '%s/%s' result: %s", user, repo, err.Error())
http.ServeContent(w, r, "unavailable", time.Now(), bytes.NewReader([]byte("500 Something went wrong...")))
return
}
tmpl, err = tmpl.Parse(templates.GenericResults)
if err != nil {
log.ShowWrite("[Error] '%s/%s' result: %s\n", user, repo, err.Error())
log.ShowWrite("[Error] '%s/%s' result: %s", user, repo, err.Error())
http.ServeContent(w, r, "unavailable", time.Now(), bytes.NewReader([]byte("500 Something went wrong...")))
return
}
Expand All @@ -386,7 +386,7 @@ func renderNIXResults(w http.ResponseWriter, r *http.Request, badge []byte, cont

err = tmpl.ExecuteTemplate(w, "layout", info)
if err != nil {
log.ShowWrite("[Error] '%s/%s' result: %s\n", user, repo, err.Error())
log.ShowWrite("[Error] '%s/%s' result: %s", user, repo, err.Error())
http.ServeContent(w, r, "unavailable", time.Now(), bytes.NewReader([]byte("500 Something went wrong...")))
return
}
Expand All @@ -398,13 +398,13 @@ func renderODMLResults(w http.ResponseWriter, r *http.Request, badge []byte, con
tmpl := template.New("layout")
tmpl, err := tmpl.Parse(templates.Layout)
if err != nil {
log.ShowWrite("[Error] '%s/%s' result: %s\n", user, repo, err.Error())
log.ShowWrite("[Error] '%s/%s' result: %s", user, repo, err.Error())
http.ServeContent(w, r, "unavailable", time.Now(), bytes.NewReader([]byte("500 Something went wrong...")))
return
}
tmpl, err = tmpl.Parse(templates.GenericResults)
if err != nil {
log.ShowWrite("[Error] '%s/%s' result: %s\n", user, repo, err.Error())
log.ShowWrite("[Error] '%s/%s' result: %s", user, repo, err.Error())
http.ServeContent(w, r, "unavailable", time.Now(), bytes.NewReader([]byte("500 Something went wrong...")))
return
}
Expand All @@ -427,7 +427,7 @@ func renderODMLResults(w http.ResponseWriter, r *http.Request, badge []byte, con

err = tmpl.ExecuteTemplate(w, "layout", info)
if err != nil {
log.ShowWrite("[Error] '%s/%s' result: %s\n", user, repo, err.Error())
log.ShowWrite("[Error] '%s/%s' result: %s", user, repo, err.Error())
http.ServeContent(w, r, "unavailable", time.Now(), bytes.NewReader([]byte("500 Something went wrong...")))
return
}
Expand Down
Loading