/*
 * Copyright (c) 2014 Spotify AB.
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package com.spotify.helios.auth.crt;

import com.spotify.crtauth.CrtAuthServer;
import com.spotify.crtauth.exceptions.ProtocolVersionException;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

@Path("/_auth")
public class CrtHandshakeResource {

  private final CrtAuthServer authServer;

  public CrtHandshakeResource(CrtAuthServer authServer) {
    this.authServer = authServer;
  }

  @GET
  public Response handshake(@Context HttpHeaders headers) {
    // initial request should have X-CHAP: request:<blob>
    final String chap = headers.getRequestHeaders().getFirst("X-CHAP");
    if (chap != null) {
      if (chap.startsWith("request:")) {
        return sendChallenge(chap);
      } else if (chap.startsWith("response:")) {
        return sendResponse(chap);
      }
    }

    return Response.status(Status.BAD_REQUEST)
        .header(HttpHeaders.CONTENT_TYPE, "text/plain")
        .entity("Bad handshake")
        .build();

  }

  private Response sendChallenge(String chap) {
    final String requestPayload = chap.substring(chap.indexOf(":") + 1);
    try {
      final String challenge = authServer.createChallenge(requestPayload);
      return Response.ok()
          .header("X-CHAP", "challenge:" + challenge)
          .build();
    } catch (IllegalArgumentException | ProtocolVersionException e) {
      // TODO (mbrown): proper response
      return Response.status(Status.BAD_REQUEST)
          .build();
    }
  }

  private Response sendResponse(String chap) {
    final String responsePayload = chap.substring(chap.indexOf(":") + 1);
    final String token;
    try {
      token = authServer.createToken(responsePayload);
      return Response.ok()
          .header("X-CHAP", "token:" + token)
          .build();
    } catch (IllegalArgumentException | ProtocolVersionException e) {
      // TODO (mbrown): proper response
      return Response.status(Status.BAD_REQUEST)
          .build();
    }
  }


}

@@ -984,16 +984,74 @@
 ption;%0A%0A
+import org.slf4j.Logger;%0Aimport org.slf4j.LoggerFactory;%0A%0A
 import j
@@ -1161,16 +1161,51 @@
 eaders;%0A
+import javax.ws.rs.core.MediaType;%0A
 import j
@@ -1325,16 +1325,106 @@
 urce %7B%0A%0A
+  private static final Logger log = LoggerFactory.getLogger(CrtHandshakeResource.class);%0A%0A
   privat
@@ -2045,20 +2045,28 @@
 PE, 
-%22text/plain%22
+MediaType.TEXT_PLAIN
 )%0A  
@@ -2156,32 +2156,38 @@
 enge(String chap
+Header
 ) %7B%0A    final St
@@ -2212,44 +2212,30 @@
 d = 
-chap.substring(chap.indexOf(%22:%22) + 1
+splitHeader(chapHeader
 );%0A 
@@ -2499,89 +2499,306 @@
     
-// TODO (mbrown): proper response%0A      return Response.status(Status.BAD_REQUEST
+log.warn(%22unable to create challenge for request with Authorization header: %7B%7D%22,%0A          chapHeader,%0A          e);%0A      return Response.status(Status.BAD_REQUEST)%0A          .entity(%22Error in generating challenge for your request%22)%0A          .header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN
 )%0A  
@@ -2869,16 +2869,22 @@
 ing chap
+Header
 ) %7B%0A    
@@ -2918,86 +2918,61 @@
 d = 
-chap.substring(chap.indexOf(%22:%22) + 1);%0A    final String token;%0A    try %7B%0A     
+splitHeader(chapHeader);%0A    try %7B%0A      final String
  tok
@@ -3193,118 +3193,609 @@
  // 
-TODO (mbrown): proper response%0A      return Response.status(Status.BAD_REQUEST)%0A          .build();%0A    %7D%0A  %7D%0A%0A
+NOTE: the crtauth library throws IllegalArgumentException for cases where the key is not%0A      // found, signing cannot be performed, etc%0A      log.warn(%22unable to create response for request with Authorization header: %7B%7D%22,%0A          chapHeader,%0A          e);%0A      return Response.status(Status.BAD_REQUEST)%0A          .entity(%22Error in generating challenge for your request%22)%0A          .header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN)%0A          .build();%0A    %7D%0A  %7D%0A%0A  private static String splitHeader(final String chapHeader) %7B%0A    return chapHeader.substring(chapHeader.indexOf(%22:%22) + 1);%0A  %7D
 %0A%7D%0A

improve error responses from CrtHandshakeResource